A Few Questions Around Go

Issue

I am learning Golang, and came across few interesting findings…
As, from 1.18 generics have been implemented… I am bit struggling around interfaces and its use. Following are my couple of findings and queries. It would be very helpful if someone clears them out. Thanks in advance.

  1. The type constrained interfaces are introduced. Which can only be used with generics (if I am not wrong). So why Go does not allow us to use it directly as below…
import "fmt"
type I interface {
    int   // if I comment this entire line, code works. otherwise panics at line 6
}
func main() {
    var i I // panics : interface contains type constraints
    i = 3
    fmt.Println(i)
}

Above example panics at line 8 (interface contains type constraints).
well, it should not panic as I am asserting int value to i which should be allowed as I implemented int type. It should only panic at runtime when I try to use other value than int at line 7.

  1. this question is about "any" and "comparable". As per the documentation, these are not the keywords. These are aliases. That means, while compiling whenever go finds "any" somewhere, it takes it as interface{} ? And if so, then how about "comparable". What exactly compiler considers it as?

Solution

As of go release 1.18, only basic interfaces (see: https://go.dev/ref/spec#Basic_interfaces) can be used as the type of a variable. A basic interface specifies only methods.

From the section of the spec under "General Interfaces":

Interfaces that are not basic may only be used as type constraints, or
as elements of other interfaces used as constraints. They cannot be
the types of values or variables, or components of other,
non-interface types.

As @mkopriva points out in a comment, this is not a panic, but a compile-time error. Your code (https://go.dev/play/p/qw3zh89n_gs) produces this error:

./prog.go:10:8: interface contains type constraints

Go build failed.

Answered By – Paul Hankin

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.