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 關注
- 155 瀏覽
添加回答
舉報