【问题标题】:What (exactly) does the type keyword do in go?type 关键字在 go 中(确切地)做了什么?
【发布时间】:2019-05-10 10:14:05
【问题描述】:
我一直在阅读A Tour of Go 以了解Go-Lang,目前进展顺利。
我目前正在上Struct Fields 课程,这里是右侧的示例代码:
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
v.X = 4
fmt.Println(v.X)
}
看看第 3 行:
type Vertex struct {
我不明白这个,type 关键字有什么作用,为什么会出现?
【问题讨论】:
标签:
go
struct
types
keyword
【解决方案1】:
type 关键字用于创建新类型。这称为type definition。新类型(在您的情况下为 Vertex)将具有与基础类型(具有 X 和 Y 的结构)相同的结构。该行基本上是在说“基于 X int 和 Y int 的结构创建一个名为 Vertex 的类型”。
不要将类型定义与类型别名混淆。当你声明一个新类型时,你不仅仅是给它一个新名字——它会被认为是一个不同的类型。请查看type identity,了解有关该主题的更多信息。
【解决方案2】:
用于定义新类型。
一般格式:
type <new_type> <existing_type or type_definition>
常见用例:
- 为现有类型创建新类型。
格式:
type <new_type> <existing_type>
例如
type Seq []int
- 在定义结构时创建一个类型。
格式:
type <new_type> struct { /*...*/}
例如
https://gobyexample.com/structs
- 定义函数类型,(也就是通过将名称分配给函数签名)。
格式:
type <FuncName> func(<param_type_list>) <return_type>
例如
type AdderFunc func(int, int) int
在你的情况下:
它为一个新的结构定义了一个名为Vertex的类型,以便以后可以通过Vertex引用该结构。
【解决方案3】:
实际上type关键字与PHP中的类拓扑相同。
使用 type 关键字就像在 GO 中创建类一样
示例输入结构
type Animal struct {
name string //this is like property
}
func (An Animal) PrintAnimal() {
fmt.Println(An.name) //print properties
}
func main() {
animal_cow := Animal{ name: "Cow"} // like initiate object
animal_cow.PrintAnimal() //access method
}
好的,让我们使用 type string(int 或 float 相同)
type Animal string
// create method for class (type) animal
func (An Animal) PrintAnimal() {
fmt.Println(An) //print properties
}
func main(){
animal_cow := Animal("Cow") // like initiate object
animal_cow.PrintAnimal() //access method
//Cow
}
struct 和 string、int、float 的区别只是在 struct 中您可以添加更多具有任何不同数据类型的属性
在 string, int, float 中相反,您只能拥有 1 个属性,这些属性是在您启动类型时创建的(例如:animal_cow := Animal("Cow")
但是,所有使用 type 关键字构建的类型肯定可以有不止一种方法
如果我错了,请纠正我