我尝试了以下Rust类型别名:
type Name = String;
效果很好。所以我尝试了一个变体:
type Name = &str;
但失败的原因是:
error[E0106]: missing lifetime specifier
--> src/main.rs:1:17
|
1 | type Name = &str;
| ^ expected lifetime parameter
为什么类型别名需要一个生存期参数,我将如何添加它?
我见过一些Rust示例中使用的关键字type,但我从来没有看到过它的解释。下面是我看过的一些使用它的例子:
impl Add<Foo> for Bar {
type Output = BarFoo;
// omitted
}
还有这个,
type T = HashMap<i32,String>; // Type arguments used in a type expression
let x = id::<i32>(10); // Type arguments used in a call expression
有人能解释一下
如何将非原始类型指定为Rust函数参数-特别是HashMap?例如:
use std::collections::HashMap;
// a main function that would call fibbonacci...
// Here the hashmap would be used for memoizing;
// maybe ugly, but it's a first attempt
fn fibbonacci(n: i32, cache: ??) -> i32 {
}
我试过:
cache: Hashmap => wrong number of
当从这样的函数返回值时
let x = String::from("Hello");
let y = do_something(x);
使用
fn do_something(s: String) -> String { s }
Rust是做一个浅拷贝(即将s的堆栈值复制到y中),还是做其他的事情?在传递时会创建一个浅表副本,但返回它时是否会有相同的行为呢?
我仍在学习Rust,并试图使用rust-cssparser重用源库中定义的impl,但得到编译错误cannot define inherent impl for a type outside of the crate where the type is defined。当然,库使用use super::Token;,但是我需要use cssparser::{ Token };,而且不知道如何解决。
节选:
impl<'a> Token<'a> {
/// Categorize a token into a type that determines
尝试从标准正态分布生成随机数。需要将该值乘以0.1,才能得到我要查找的数字范围。我尝试使用您可以在此处找到的rand_dist文档:https://docs.rs/rand 我的Cargo.toml如下: [package]
name = "test_rng"
version = "0.1.0"
authors = ["Jack"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/referenc
我有一些代码应该从数据库中获取图像文件名并将它们添加到向量中。
extern crate postgres;
use postgres::{Connection, TlsMode};
fn main() {
let conn = Connection::connect(
"postgres://postgres:password@localhost:5432/test",
TlsMode::None,
).unwrap();
let mut filenames = Vec::new();
if let Ok(