Static function of the generic struct


#1
struct Test<T> {
    t: T,
}

impl<T> Test<T> {
    fn test () {}
}

fn main() {
    Test::<f64>::test();
}

Sorry for another stupid question, but why I have to monomorphize in this case? Static function test() is not generic.


#2

[quote=“soos, post:1, topic:3658”]
Static function test() is not generic.
[/quote]What exactly do you mean by this? It is inside a generic impl block after all, although since T is unbounded, the function can hardly do anything useful with it.


#3

I believe it’s because test() could need to know what T is and the compiler doesn’t want to look inside test() to figure that out. If you were to write:

use std::mem;

struct Test<T> {
    t: T,
}

impl<T> Test<T> {
    fn test () {
        println!("size {}", mem::size_of::<T>());	
    }
}

fn main() {
    Test::<f64>::test();
}

T needs to be defined when calling test().

I guess the bigger question is why is test() associated with Test and not defined as a basic function outside of of the impl? The only reason to define it inside impl Test would be because it’s going to create a temporary Test structure or use the size of T or Test.


#4

I believe there are hopes to have the compiler identify “not really generic” functions like these and prevent them from being duplicated, but there aren’t any concrete plans as this isn’t particularly high-priority. @brson is probably the dude to ask about any details here.


#5

That you’re not using T in the body of the function is an implementation detail — you could begin doing so in any later version of this code, without changing the signature of the function. Client code should not have to update.