GO語言struct文法

來源:互聯網
上載者:User

標籤:struct

struct

-使用type<Name>struct{}定義結構,名稱遵循可見度規則

-支援指向自身的指標類型成員

-支援匿名結構、可作用成員或定義成員變數

-匿名結構也可以用於MAP的值

-可以使用字面值對結構進行初始化

-允許值通過指標來讀寫結構成員

-相同類型的成員可進行直接拷貝賦值

-支援==與!=比較子,不支援>或<

-支援匿名欄位,本質上是定義了以某個類型名稱的欄位

-嵌入結構作為匿名欄位看起來像繼承、但不是繼承

-可以使用匿名欄位的指標

package main

import "fmt"

type test struct{}


func main(){

a :=test{}

fmt.Println(a)


}


package main
import "fmt"
type test struct {
    Name    string
    Age     int
    Address string
}
func main() {
    a := test{}
    a.Name = "YH" //值初始化,與其他語言的class類似,GO語言沒有指標運算,
    a.Age = 18
    fmt.Printf("我叫%s, 今年年方%d\n", a.Name, a.Age)
    b := test{
        Name:    "YH",
        Age:     19,
        Address: "Japan",
    }
    fmt.Printf("我叫%s, 今年年方%d,我是%s\n人", b.Name, b.Age, b.Address)
}


//匿名結構

package main
import "fmt"
type test struct {
    Name    string
    Age     int
    Address string
    Contact struct {
        User_phont string
        City       string
    }
}
func main() {
    a := test{Name: "yh", Age: 19, Address: "Bj"}
    a.Contact.User_phont = "1234567890"
    a.Contact.City = "haidian"
    fmt.Println(a)
}



package main

import "fmt"

func main() {

a := struct {

Name string

Age  int

}{

Name: "aa",

Age:  19,

}

fmt.Println(a)

}


package main

import "fmt"

type test struct{

Name string

Age int

}


func main(){

a :=test{

Name:"coolqi",  //設定字面值初始化

}

a.Age=19//

fmt.Println(a)


}



package main

import "fmt"

type humen struct{

Sex int

}


type Teacher struct{

humen

Name string

Age int



}

type Student struct{

humen    //這裡的嵌入式是一個匿名的欄位,本質上是將結構的名稱作為欄位名稱,若需要作為字面值初始化,需要做humen:humen{Sex:1}

Name string

Age int

}

func main(){

a :=Teacher{Name:"joe",Age:19,humen:humen{Sex:1}}//在嵌入式結構中,

fmt.Println(a)


}


本文出自 “DBAspace” 部落格,請務必保留此出處http://dbaspace.blog.51cto.com/6873717/1963454

GO語言struct文法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.