Generics implementing interface #23278
Unanswered
sudokit
asked this question in
Questions and Answers
Replies: 2 comments
-
You could check if pub interface Boo {
pos() (f32, f32)
}
struct Foo[T]{ x f32 y f32 }
struct Origin { }
fn (o Origin) pos() (f32, f32) { return 0, 0 }
struct Int { x int y int }
fn (i Int) pos() (f32, f32) { return f32(i.x), f32(i.y) }
fn new_foo[T](t T) !Foo[T] {
$if t is Boo {
x, y := t.pos()
return Foo[T]{ x:x, y:y }
}
return error('${t} is not Boo')
}
fn main() {
s := new_foo(Origin{})!
println('${s}')
i := new_foo(Int{1,2})!
println('${i}')
x := new_foo('string') or { println('${err}'); exit(1) }
println('${x}')
} Result:
Both |
Beta Was this translation helpful? Give feedback.
0 replies
-
Another approach with options and saving boo in foo to call pub interface Boo {
pos() (f32, f32)
}
struct Foo[T]{ boo Boo }
struct Origin { }
fn (o Origin) pos() (f32, f32) { return 0, 0 }
struct Int { x int y int }
fn (i Int) pos() (f32, f32) { return f32(i.x), f32(i.y) }
fn new_foo[T](t T) ?Foo[T] {
$if t is Boo {
return Foo[T]{ boo: t }
}
return none
}
fn main() {
if o := new_foo(Origin{}) { println(o.boo.pos()) } // (0.0, 0.0)
if i := new_foo(Int{1,2}) { println(i.boo.pos()) } // (1.0, 2.0)
if s := new_foo('string') { println(s.boo.pos()) } // empty
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Is it possible to constrain a generic to implement a interface?
something like this:
Beta Was this translation helpful? Give feedback.
All reactions