Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot access struct field when using Borrow constraint

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;
  |               ^^^^

code on rust playground

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading