< 返回版块

github.com/shanliu/lsys 发表于 2023-03-01 10:16

option可以这样简写

fn aaa(_a: Option<impl ToString>) {}

#[test]
fn aaaaaa() {
    aaa(None::<&str>);
}

数组怎么搞?

fn aaa(_a: &[impl ToString]) {}

#[test]
fn aaaaaa() {
    let b: &[&str] = &[];
    aaa(b);
    //有没办法不声明临时变量,类似以下写法
    //aaa(&[]);
}

评论区

写评论
yangweng 2023-03-02 22:42

#![feature(type_alias_impl_trait)] TAIT 还不稳定。只能再测试版上用。不然你用这个就很方便了。

作者 github.com/shanliu/lsys 2023-03-02 21:58

我是想知道impl的简写 范型方式我知道。。。😂

--
👇
zhylmzr: ```rust fn aaa<T: ToString>(_a: &[T]) {}

fn aaaaaa() { aaa::<&str>(&[]); }


zhylmzr 2023-03-02 11:29
fn aaa<T: ToString>(_a: &[T]) {}

fn aaaaaa() {
    aaa::<&str>(&[]);
}
PrivateRookie 2023-03-01 14:28
aaa(&[""; 0]);
作者 github.com/shanliu/lsys 2023-03-01 13:36

as .... 哎. 其实我想找类似::<..>方式

👇
Pikachu: ``` fn aaa(_a: &[impl ToString]) {}

#[test] fn aaaaaa() { aaa(&[] as &[&str]); }


[rust playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=bccdfb219d5f8ed61a0f355312e4ed0c)
viruscamp 2023-03-01 10:58

调用时一定要有一个实际类型

数组有值就能推导类型,直接写

    aaa(&["abc"]);
    
    aaa(&[String::from("abc")]);

空数组没法推导类型,指定类型

    aaa(&[] as &[&str]);
Pikachu 2023-03-01 10:55
fn aaa(_a: &[impl ToString]) {}

#[test]
fn aaaaaa() {
    aaa(&[] as &[&str]);
}

rust playground

1 共 7 条评论, 1 页