What is this strange syntax where an enum variant is used as a function?

*爱你&永不变心* 提交于 2019-12-01 21:24:57

This syntax is standard Rust syntax. You can use tuple struct or tuple struct-like enum variants as functions. See this small example:

enum Color {
    Str(String),
    Rgb(u8, u8, u8),
}

struct Foo(bool);

// Use as function pointers (type annotations not necessary)
let f: fn(String) -> Color = Color::Str;
let g: fn(u8, u8, u8) -> Color = Color::Rgb;
let h: fn(bool) -> Foo = Foo;

In the next example, those functions are directly passed to another function (like Option::map) (Playground):

// A function which takes a function
fn string_fn<O, F>(f: F) -> O
where
    F: FnOnce(String) -> O,
{
    f("peter".to_string())
}


string_fn(|s| println!("{}", s));  // using a clojure 
string_fn(std::mem::drop);         // using a function pointer

// Using the enum variant as function
let _: Color = string_fn(Color::Str); 

You can find out more about this feature, in this chapter of the book.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!