Skip to content

Instantly share code, notes, and snippets.

@jimmycuadra
Created February 14, 2017 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimmycuadra/95b8d25291a7af2290323a96aebeafdf to your computer and use it in GitHub Desktop.
Save jimmycuadra/95b8d25291a7af2290323a96aebeafdf to your computer and use it in GitHub Desktop.
Resolving a series of associated types
trait HasEndpoint {
type Endpoint: Endpoint;
}
trait Endpoint {
type Request: Default + ToString;
}
struct Foo;
struct MyEndpoint;
type MyRequest = u64;
impl Foo {
pub fn request(&self) -> String {
// What is the syntax for resolving `Request` without naming it explicitly?
let request = self::Endpoint::Request::default();
// ^ This results in:
//
// error[E0223]: ambiguous associated type
// |
// | let request = self::Endpoint::Request::default();
// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ambiguous associated type
// |
// = note: specify the type using the syntax `<Type as Endpoint>::Request`
let request = <self as Endpoint>::Request::default();
// ^ This results in:
//
// error: expected type, found module
// |
// | let request = <self as Endpoint>::Request::default();
// | ^^^^
let request = <self as HasEndpoint>::Endpoint::Request::default();
// ^ This results in:
//
// error: expected type, found module
// |
// | let request = <self as HasEndpoint>::Endpoint::Request::default();
// | ^^^^
request.to_string()
}
}
impl HasEndpoint for Foo {
type Endpoint = MyEndpoint;
}
impl Endpoint for MyEndpoint {
type Request = MyRequest;
}
fn main() {
let foo = Foo;
println!("{}", foo.request());
}
@jimmycuadra
Copy link
Author

jimmycuadra commented Feb 14, 2017

Answer:

self can't be used in this context, because that refers to the value, not the type. Self can be used, or the concrete type. These work:

let request = <<Self as HasEndpoint>::Endpoint as Endpoint>::Request::default();
let request = <<Foo as HasEndpoint>::Endpoint as Endpoint>::Request::default();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment