Home > Software design >  Interfaces in golang and generics
Interfaces in golang and generics

Time:06-20

I was going through this tour of go.

Initially i is declared an interface with type string. var i interface{} = "hello"

But when we do

f = i.(float64) // panic

My question is, why isn't this caught during compile time in golang. C generics catch this during compile time, unlike go which decides to do it at runtime.

The "type" information for i exists during compilation. This kind of issue would be something that would make it easier (from a golang programmer's perspective) to catch during compilation than runtime.

edit: Eduardo Thales suggested that generics were included later in golang. I was under the assumption that the underlying mechanism of interfaces is generics. apparently not. Thanks Eduardo

CodePudding user response:

The language specification explicitly says that false type assertions cause a run-time panic. See:

If the type assertion is false, a run-time panic occurs.

Also, there's nothing in the language that says that you can't make a program that will unambiguously panic. For example, this is a valid program that will compile without error:

package main

import "fmt"

func main() {
    fmt.Println("Don't panic!")
    panic(1)
}

CodePudding user response:

You're mixing up generics and variable types. Take this as an example:

items := []string{"item1", "item2"}
fmt.Println(slices.Contains(items, "item1"))

The variable type is slice. The generic part is string, which is regarded in slices.Contains. So, fmt.Println(slices.Contains(items, 1)) would cause a compile time error because the generic type string doesn't match the generic type int.

(NB: slice is not the best representative of a typical generic in Go because usually they look different, but it's the easiest one to grasp the concept.)

@mkopriva has already answered why your code doesn't cause a compile error: float64 is a valid subtype of interface{}. If it wasn't, you'ld get a compile time error here as well, e.g. as in

var i string = "hello"
f := i.(float64) // compile time error

Generics don't even exist here, though, and neither they did in your example.

  •  Tags:  
  • go
  • Related