关于Go语言类型创建规范

huangapple go评论80阅读模式
英文:

about golang type create Specification

问题

示例代码:

package main

import "fmt"

type ipoint int

type Futest struct {
	Name string
}

func main() {
	i := ipoint(1)
	fmt.Println(i) //打印 1

	futest := Futest{
		Name: "test",
	}
	fmt.Println(futest) //打印 {test}
}

我的问题是:为什么ipoint对象只需要ipoint(1)来创建,而Futest结构需要更复杂的语句

Futest{
	Name: "test",
}

是否有golang规范描述它

英文:

the example code

package main

import "fmt"

type ipoint int

type Futest struct {
	Name string
}

func main() {
	i := ipoint(1)
	fmt.Println(i) //print 1

	futest := Futest{
		Name: "test",
	}
	fmt.Println(futest) //print {test}
}

my question is :
why ipoint object only ipoint(1) create,but Futest struct need more complex statmenet

Futest{
		Name: "test",
	}

any golang Specification describe it

答案1

得分: 2

ipoint是一种int类型,Futest是一种struct类型。我们可以将整数转换为ipoint并赋值给一个名为i的新变量,如下所示。

i := ipoint(1)

我们可以按如下所示从struct创建一个新实例。


  futest := Futest{
        Name: "test",
  }

  // 或者

  futest := Futest{"test"}

  // 如果struct有多个字段,
  // 我们需要保持字段的顺序。
  // 
  //  例如:
  //
  //   type A struct {
  //    Number int
  //    Name string
  //   }
  // 
  //   a := A{1,"sample"} 
英文:

ipoint is a type of int and Futest is a type of struct. We can covert integer to ipoint and assign to new variable called i as shown below.

i := ipoint(1)

We can create a new instance from struct as shown below.


  futest := Futest{
        Name: "test",
  }

  // or

  futest := Futest{"test"}

  // If the struct has more than one fields,
  // We need to maintain the order of fields.
  // 
  //  Example:
  //
  //   type A struct {
  //    Number int
  //    Name string
  //   }
  // 
  //   a := A{1,"sample"} 

huangapple
  • 本文由 发表于 2023年3月18日 19:28:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75775565.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定