Why I cannot access path field? Can I do something with that?
use std::borrow::Borrow;
struct Node{
path: String,
}
fn foo<T: Borrow<Node>>(a: T) {
let x = a.path;
}
fn main(){
let mut i = 5;
let mut node = Node {path:"test".to_string()};
foo(&node);
foo(&mut node);
}
error[E0609]: no field `path` on type `T`
--> src/main.rs:8:15
|
7 | fn foo<T: Borrow<Node>>(a: T) {
| - type parameter 'T' declared here
8 | let x = a.path;
| ^^^^
>Solution :
The Borrow
trait does not provide any syntactical sugar, it simply defines a borrow()
method that returns the &T
. So getting the path
field would be:
a.borrow().path
With that said, you may also be interested in the Deref
trait, which does have syntactical sugar to access the field directly:
fn foo<T: Deref<Target = Node>>(a: T) {
let x = &a.path;
}
See it working on the playground.