将命名类型分配给文字类型值

时间:2019-05-30 22:33:41

标签: go

在这里新手。我正在尝试将uint64值分配给具有基础类型unit64的命名类型的变量。编译器不满意,看不到两种类型完全相同。什么是正确的方法?

package main

import "fmt"
import "math/rand"

type myType uint64

var x myType


func main() {
    x = rand.Uint64()
    fmt.Println(x)
}

这会引发编译器错误:

./prog.go:12:4: cannot use rand.Uint64() (type uint64) as type myType in assignment

1 个答案:

答案 0 :(得分:3)

您可以myType(rand.Uint64())对其进行转换。有用的链接:Type Assertion in GoType Conversion in Go,以及此堆栈溢出问题"How to cast to a type alias in go"

的出色答案