rust 函数泛型中的clone 报错

rust 函数泛型中的clone 报错

起因

想要一个二叉树,需要从&Box<T>返回一个Box<T>,类似的代码是

fn cloned<T>(r:&Box<T>)->Box<T> {
    
    
	r.clone()
}

fn main() {
    
    }

经过

编译之后就报错

  Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
 --> src/main.rs:2:2
  |
1 | fn cloned<T>(r:&Box<T>)->Box<T> {
    
    
  |                          ------ expected `Box<T>` because of return type
2 |     r.clone()
  |     ^^^^^^^^^ expected struct `Box`, found `&Box<T>`
  |
  = note: expected struct `Box<T>`
          found reference `&Box<T>`

看不懂这个错误,不过之后自己发现了错误

结果

正确的应该是

fn cloned<T>(r:&Box<T>)->Box<T> 
where T:Clone {
    
    
	r.clone()
}

fn main() {
    
    }

Guess you like

Origin blog.csdn.net/agctXY/article/details/118896020