go - Go 中的函数调用、赋值和 'underlying types'

标签 go types

我正在学习 Go(到目前为止很喜欢),但我遇到了一个有趣的问题。编译失败的代码是:

package main

import "fmt"

type MyInt int

func (i MyInt) Double() MyInt {
    return i + i
}

func AddTwo(i int) int {
    return i + 2
}

func main() {
    var a int = 3
    var x MyInt = a  // Why does this fail?
    fmt.Println(x.Double())
    var y int = AddTwo(x)  // Why does this fail?
    fmt.Println(y)
}

这是 Go Playground 链接:MyInt

当我尝试运行它时,出现以下错误:

  prog.go:17: cannot use a (type int) as type MyInt in assignment
  prog.go:19: cannot use x (type MyInt) as type int in argument to AddTwo

但是,如果我正确阅读了规范,那么这段代码应该可以编译。首先,MyInt的底层类型是int according to this section .事实上,给出的示例之一是 type T1 string,它表示 T1 的基础类型是 string。那么,为什么我不能将a 分配给x 呢?他们没有相同的底层类型吗?对 AddTwo() 的函数调用也是如此。 x 不是有底层类型 int 吗?为什么我不能将它用作 int 参数?

另外,Double() 怎么编译?在表达式 i + i 中,我添加了两个 MyInt 值。它编译的事实表明 MyInt 至少在某种意义上是 int

总之,我有点困惑。所以我认为像 type MyInt int 这样的声明的意义在于,现在您可以向基本类型添加方法。但是,如果您无法将它们视为 int(需要转换),那么拥有这整个“底层类型”业务的意义何在?

最佳答案

Go 有严格的类型系统。仅仅因为您的类型只是 int 的别名并不意味着您可以自由地互换两者,您仍然必须进行类型转换。下面是你的主要工作版本,这里是 Playground 上的代码; https://play.golang.org/p/kdVY145lrJ

func main() {
    var a int = 3
    var x MyInt = MyInt(a)  // Why does this fail?
    fmt.Println(x.Double())
    var y int = AddTwo(int(x))  // Why does this fail?
    fmt.Println(y)
}

关于go - Go 中的函数调用、赋值和 'underlying types',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33402126/

相关文章:

go - 如何在 Go 中找到接口(interface)的根实现?

go - $GOPATH 值在终端的新 session 期间不断重置为空

c# - 在 C# 中使用相同布局强制不同命名空间中的类型

C#、.net、通用编程架构。 GetType 或枚举 : Which is better?

Golang gin 传递默认值

net 包中的 Golang 类型

c - SIGTRAP : trace trap error in Golang wrapping C library, 但仅在运行 go test 时

python - 实现具有固定键类型(例如枚举类型)的字典的最佳方法?

types - 在 Rust 的枚举中使用现有类型

java - 动态规划 非常大的数据值(value)