简体   繁体   中英

Go composite literal for type of primitive value

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM