I am a new to Go and have a question. Maybe it is not a idiomatic Go code but just for studying purposes how to make this code work? It seems that I can put as a receiver type of int, but how to call it in main?:
xa.go
package main
import "fmt"
type xa int
func (xl xa) print() {
fmt.Println(xl)
}
main.go
package main
func main() {
X := (xa{2})//not working
X.print()
}
Run:
go run main.go xa.go
.\main.go:10:8: invalid composite literal type xa
Use a type conversion:
x := xa(2) // type conversion
x.print()
Or give a type to your variable, and you may use an untyped constant assignable to (a variable of type) xa
:
var y xa = 3 // 3 is an untyped constant assignable to xa
y.print()
Try the examples on the Go Playground.