为了账号安全,请及时绑定邮箱和手机立即绑定

type 关键字在 go 中(究竟)做了什么?

type 关键字在 go 中(究竟)做了什么?

Go
陪伴而非守候 2023-05-15 14:55:34
我一直在阅读Go Tour of Go来学习Go-Lang,到目前为止进展顺利。我目前正在学习结构字段课程,这是右侧的示例代码:package mainimport "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关键字是做什么的,为什么会在那里?
查看完整描述

3 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

关键字type用于创建新类型。这称为类型定义。新类型(在您的例子中为 Vertex)将具有与基础类型(具有 X 和 Y 的结构)相同的结构。该行基本上是在说“基于 X int 和 Y int 的结构创建一个名为 Vertex 的类型”。

不要混淆类型定义和类型别名。当您声明一个新类型时,您不仅仅是给它一个新名称——它将被视为一个独特的类型。查看类型标识以获取有关该主题的更多信息。


查看完整回答
反对 回复 2023-05-15
?
幕布斯6054654

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


查看完整回答
反对 回复 2023-05-15
?
慕桂英3389331

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 关键字构建的类型都可以有不止一种方法


如果我错了请纠正我


查看完整回答
反对 回复 2023-05-15
  • 3 回答
  • 0 关注
  • 126 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信