0

This code (derived from a more complex example) compiles [playground]:

fn func1<'a>(s: &'a str) where 'static: 'a { println!("{s}"); }

fn func2<'a>(s: &'a str) { func1(s) }

trait MyTrait {
    fn func<'a>(s: &'a str) where 'static: 'a;
}

impl MyTrait for () {
    fn func<'a>(s: &'a str) where 'static: 'a { println!("{s}"); }
    
}

fn main() {
    func2("hello");
    <()>::func("world");
}

but this one does not [playground]:

fn func1<'a>(s: &'a str) where 'static: 'a { println!("{s}"); }

fn func2<'a>(s: &'a str) { func1(s) }

trait MyTrait {
    fn func<'a>(s: &'a str) where 'static: 'a;
}

impl MyTrait for () {
    fn func<'a>(s: &'a str) { println!("{s}"); }
    
}

fn main() {
    func2("hello");
    <()>::func("world");
}

As func1 and func2 show, constraint 'static: 'a appears to be a blank constraint. So why is it necessary when implementing the trait?


Further comment on the question: if this is a simple signature problem relating to where clauses, why does this example compile? [playground]

use std::fmt::Debug;
trait MyTrait<T> {
    fn func<'a>(s: &'a str) where T: 'a + Debug;
}

impl MyTrait<f64> for () {
    fn func<'a>(s: &'a str) where 'static: 'a { println!("{s}"); }
    
}

trait MyTrait2<T> {
    fn func2(s: &str) where T: Debug;
}

impl MyTrait2<f64> for () {
    fn func2(s: &str) { println!("{s}"); }
    
}

fn main() {
    <()>::func("hello");
    <()>::func2("world");
}

and not this one: [playground]

use std::fmt::Debug;
trait MyTrait<T> {
    fn func<'a>(s: &'a str) where T: 'a + Debug;
}

impl MyTrait<f64> for () {
    fn func<'a>(s: &'a str) where f64: Debug { println!("{s}"); }
    
}

fn main() {
    <()>::func("hello world");
}
6
  • 1
    Because where is part of the signature, you must match the signature exatly. Commented Jan 7 at 18:16
  • I completed the question with a new example, wich compile with different signatures. Commented Jan 7 at 18:23
  • Well carefully observe every one of the working versions does have a where in the implementation. Commented Jan 7 at 21:02
  • Thank you for your answers, cafce25. I updated the question with an example working, without 'where' in the implementation. Commented Jan 7 at 22:43
  • 1
    Your latest example doesn't need the where clause because there are no unbound generic parameters: f64 is a known type and the compiler knows that f64: Debug so all is fine. In the non-working cases, 'a is unknown so the constraint must be specified (the compiler never checks if a constraint is valid for all possible values, it only checks if the constraint is valid for the known values). Commented Jan 8 at 9:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.