Skip to content

restrict type parameter Self error is unclear. #65044

Closed
@Firstyear

Description

@Firstyear

The following example code yields an error:

struct Demo {
    a: String
}

trait GetString {
    fn get_a(&self) -> &String;
}

trait UseString {
    fn use_string(&self) {
        println!("{:?}", self.get_a());
    }
}

impl GetString for Demo {
    fn get_a(&self) -> &String {
        &self.a
    }
}

impl UseString for Demo {}


#[cfg(test)]
mod tests {
    use crate::{Demo, UseString};

    #[test]
    fn it_works() {
        let d = Demo { a: "test".to_string() };
        d.use_string();
    }
}
warning: build failed, waiting for other jobs to finish...
error[E0599]: no method named `get_a` found for type `&Self` in the current scope
  --> src/lib.rs:12:31
   |
12 |         println!("{:?}", self.get_a());
   |                               ^^^^^
   |
   = help: items from traits can only be used if the type parameter is bounded by the trait
help: the following trait defines an item `get_a`, perhaps you need to restrict type parameter `Self` with it:
   |
10 | Self: GetString
   |

error: aborting due to previous error

It's unclear from this error message how to proceed - I'm not sure of the syntax, location, or where I should be putting the "GetString" trait bound.

It should be shown with a better example or link when this error is presented, as the current message is not sufficient for a resolution to be arrived at.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions