1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen: fix generic sumtype auto str (#16355)

This commit is contained in:
yuyi 2022-11-08 16:49:09 +08:00 committed by GitHub
parent dc9997f58c
commit 1d04b71c91
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 2 deletions

View File

@ -76,8 +76,14 @@ fn (mut g Gen) get_str_fn(typ ast.Type) string {
str_fn_name = styp_to_str_fn_name(sym.name) str_fn_name = styp_to_str_fn_name(sym.name)
} }
} }
if sym.has_method_with_generic_parent('str') && mut sym.info is ast.Struct { if sym.has_method_with_generic_parent('str') {
str_fn_name = g.generic_fn_name(sym.info.concrete_types, str_fn_name) if mut sym.info is ast.Struct {
str_fn_name = g.generic_fn_name(sym.info.concrete_types, str_fn_name)
} else if mut sym.info is ast.SumType {
str_fn_name = g.generic_fn_name(sym.info.concrete_types, str_fn_name)
} else if mut sym.info is ast.Interface {
str_fn_name = g.generic_fn_name(sym.info.concrete_types, str_fn_name)
}
} }
g.str_types << StrType{ g.str_types << StrType{
typ: unwrapped typ: unwrapped

View File

@ -0,0 +1,33 @@
module main
struct None {}
pub type Maybe<T> = None | T
pub fn (m Maybe<T>) str<T>() string {
return if m is T {
x := m as T
'Some($x)'
} else {
'Noth'
}
}
pub fn some<T>(v T) Maybe<T> {
return Maybe<T>(v)
}
fn test_generic_sumtype_str() {
a := some(123)
b := some('abc')
println(a.str())
println(a)
println('$a')
assert '$a' == 'Some(123)'
println(b.str())
println(b)
println('$b')
assert '$b' == 'Some(abc)'
}