i want make function can take int-like variable.
for example:
type integertype interface { int } func myfunc(arg integertype) { fmt.println(arg) } this won't compile because can't base interface inheritance on non-interface type, that's want do!
the end goal this:
type token int var t token t = 3 myfunc(t) how guarantee argument integer, while still allowing integer aliases?
how guarantee argument integer, while still allowing integer aliases?
you rely on type conversion.
func myfunc(arg int) { fmt.println(arg) } type token int var t token t = 3 myfunc(int(t)) s := "this string, obviously" myfunc(int(s)) // throws compiler error there's no need define interface type int because can rely on languages type conversion behavior enforce compile time type safety in these types of scenarios.
one thing note more accepting int interface be. example, int64 convert int, float using typical rounding conventions. invalid conversions produce following error; cannot convert s (type string) type int. can tell native numeric types or aliases them convert.
Comments
Post a Comment