0

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
  • consider this variation for further study. https://play.golang.org/p/nMRoqTgOue4 –  Apr 28 '21 at 10:54
  • There is no composite literal for underlying type `int` because it's not a composite type. The curly brace syntax is for composite literals (structs, slices, arrays, and maps). – Adrian Apr 28 '21 at 13:27

1 Answers1

2

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.

icza
  • 389,944
  • 63
  • 907
  • 827