by kiitos · 3y ago · 0 comments
func main() {
c := color.Red
cptr := (*string)(&c)
*cptr = "orange"
PrintColor(c) // successfully compiles, and prints "orange"
}...then it's broken, because the Go compiler, factually, cannot (in general) check or enforce the validity of specific values.
> there's no reason for you to also include runtime checks. Other developers breaking your defined contract is not your responsibility, it's not even a bug.
It is absolutely the responsibility of the function
func PrintColor(c Color)
to ensure, at runtime, that `c` is a valid Color. My example code -- which allowed an invalid Color value of "orange" -- is absolutely a bug in PrintColor.Casting is by definition an escape hatch.
c = Color("orange") does not compile.
package color
type Color interface {
void()
}
type color struct {
v string
}
func (c color) void() {}
func (c color) String() string {
return c.v
}
var (
Red color = color{"red"}
Green color = color{"green"}
Blue color = color{"blue"}
) func fn(c color.Color) {
switch c {
case color.Red, color.Green, color.Blue:
log.Printf("c=%#+v -- OK", c)
default:
log.Printf("c=%#+v -- should not be possible", c)
}
}
func main() {
var c color.Color
fn(c)
}
Output: c=<nil> -- should not be possible
:shrug: c := color.Red
c = Color("orange")
PrintColor(c)Doesn't matter, the point is they're getting in a value which is not part of the defined set, demonstrating that this emulation is not actually typed-safe.
> If that's the point you're intending to make, then couldn't you make it more easily with this?:
cannot convert "orange" (untyped string constant) to type ColorIn Go, they are not. Aliases establish precise equivalence between types, type redefinitions establish new types altogether.