有没有办法根据泛型类型选择常量的值?
例如,类似(无效的 Rust 代码):
fn foo<T>() {
let b = match T {
u32 => 0x01234567u32,
u64 => 0x0123456789abcdefu64,
_ => panic!()
}
}
fn main() {
foo::<u32>();
foo::<u64>();
}
Run Code Online (Sandbox Code Playgroud)
该函数仅设计用于与u16,u32和u64类型一起操作。
我正在尝试实现fmt::DisplayRust 的特征enum:
use std::fmt;
use std::error::Error;
use std::fmt::Display;
enum A {
B(u32, String, u32, u32, char, u32),
}
impl Display for A {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
A::B(a, b, c, d, e, f) => write!(f, "{} {} {} {} {} {}", a, b, c, d, e, f),
}
}
}
fn main() -> Result<(), Box<dyn Error>> {
let a = A::B(0, String::from("hola"), 1, 2, 'a', 3);
Ok(())
}
Run Code Online (Sandbox Code Playgroud)
但我收到了这个我无法理解的错误: …
我想测试一个采用std::env::Args迭代器作为参数但不使用命令行并使用以下参数提供参数的函数Vec:
use std::env;
fn main() {
let v = vec!["hello".to_string(), "world".to_string()];
print_iterator(env::args()); // with the command line
print_iterator( ??? ); // how should I do with v?
}
fn print_iterator(mut args: env::Args) {
println!("{:?}", args.next());
println!("{:?}", args.next());
}
Run Code Online (Sandbox Code Playgroud) 我想为练习排序一个字符串向量.这些字符串只有0到9之间的数字,如[10 2 1 9 91],我想排序为[9 91 2 1 10]以达到最大数字(9912110).我使用该sort函数执行了以下代码
#include <algorithm>
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
bool compare(string i1, string i2)
{
int a, b;
int i = 0;
int min_len = (i1.length() > i2.length()) ? i2.length(): i1.length();
while(i < min_len) {
a = (int) (i1.at(i) - '0');
b = (int) (i2.at(i) - '0');
if (a != b)
break;
i++;
}
if (a > b)
return true;
if (a < b) …Run Code Online (Sandbox Code Playgroud)