3 回答
TA贡献1831条经验 获得超10个赞
关键字type
用于创建新类型。这称为类型定义。新类型(在您的例子中为 Vertex)将具有与基础类型(具有 X 和 Y 的结构)相同的结构。该行基本上是在说“基于 X int 和 Y int 的结构创建一个名为 Vertex 的类型”。
不要混淆类型定义和类型别名。当您声明一个新类型时,您不仅仅是给它一个新名称——它将被视为一个独特的类型。查看类型标识以获取有关该主题的更多信息。
TA贡献1876条经验 获得超7个赞
它用于定义新类型。
一般格式:type <new_type> <existing_type or type_definition>
常见用例:
为现有类型创建新类型。
格式:type <new_type> <existing_type>
如type Seq []int
在定义结构时创建类型。
格式:type <new_type> struct { /*...*/}
定义函数类型,(也就是通过将名称分配给函数签名)。
格式:type <FuncName> func(<param_type_list>) <return_type>
如type AdderFunc func(int, int) int
在你的情况下:
它定义了一个以新结构命名的类型Vertex
,以便稍后您可以通过 引用该结构Vertex
。
TA贡献2036条经验 获得超8个赞
实际上 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
}
好的,让我们移动字符串类型(对于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 关键字构建的类型都可以有不止一种方法
如果我错了请纠正我
- 3 回答
- 0 关注
- 126 浏览
添加回答
举报