Opposite of Borrow trait for Copy types?

前端 未结 2 1212
别跟我提以往
别跟我提以往 2021-01-13 06:11

I\'ve seen the Borrow trait used to define functions that accept both an owned type or a reference, e.g. T or &T. The borrow

2条回答
  •  感情败类
    2021-01-13 06:50

    With the function you have you can only use a u32 or a type that can be borrowed as u32.

    You can make your function more generic by using a second template argument.

    fn foo>(value: N) -> T {
        *value.borrow()
    }
    

    This is however only a partial solution as it will require type annotations in some cases to work correctly.

    For example, it works out of the box with usize:

    let v = 0usize;
    println!("{}", foo(v));
    

    There is no problem here for the compiler to guess that foo(v) is a usize.

    However, if you try foo(&v), the compiler will complain that it cannot find the right output type T because &T could implement several Borrow traits for different types. You need to explicitly specify which one you want to use as output.

    let output: usize = foo(&v);
    

提交回复
热议问题