go - Golang中的类型声明和类型定义有什么区别?

标签 go

类型声明:

type A = string

类型定义:
type A string

它们之间有什么区别?我无法从规格中了解

最佳答案

type A = stringstring创建别名。每当您在代码中使用A时,它就和string一样工作。因此,例如,您不能在其上定义方法。
type A string定义了一个新类型,其表示形式与string相同。您可以以零成本在Astring之间进行转换(因为它们相同),但是您可以在新类型上定义方法,并且反射将知道A类型。

例如(在playground上)

package main

import (
    "fmt"
)

type A = string
type B string

func main() {
    var a A = "hello"
    var b B = "hello"
    fmt.Printf("a is %T\nb is %T\n", a, b)
}

输出:
a is string
b is main.B

关于go - Golang中的类型声明和类型定义有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61247864/

相关文章:

json - Golang net/http 请求 Body 总是空的

java - Golang - gomobile 基本脚本编译错误

mongodb - 无法将mongodb与GoLang连接

logging - golang 1.8 : Embedded database for logging

go - 内置库来持久化 BTree,相当于 Java 的 `FileChannel` 和 `ByteBuffer`

opengl - vertexattribpointer 中的不安全指针

go - 一段时间后如何停止等待按键

go - Golang 中 net/http 和 net/http/fcgi 的区别

go - html/模板 : optional outer element around sub-template if it's not empty

concurrency - 了解 Rob Pike 的图书焚烧示例