簡體   English   中英

Go 語言中的結構

[英]Structs in GoLang

我剛開始使用 GoLang,我正在看他們的教程之一 ( https://golang.org/doc/code.html )。

在他們的一個示例中,他們將變量設置為結構,但我很困惑他們如何在下面的 for 循環中訪問結構的元素? 有人可以澄清的機會嗎? 非常感謝!

代碼:

package stringutil

import "testing"

func TestReverse(t *testing.T) {
    cases := []struct {
        in, want string
    }{
        {"Hello, world", "dlrow ,olleH"},
        {"Hello, 世界", "界世 ,olleH"},
        {"", ""},
    }
    for _, c := range cases {
        got := Reverse(c.in)
        if got != c.want {
            t.Errorf("Reverse(%q) == %q, want %q", c.in, got, c.want)
        }
    }
}

下面是帶有一些注釋的代碼,以幫助闡明每個語句在其中的作用。

import "testing"

func TestReverse(t *testing.T) {
    cases := []struct { // declaration of anonymous type
        in, want string // fields on that type called in and want, both strings
    }{
        {"Hello, world", "dlrow ,olleH"},
        {"Hello, 世界", "界世 ,olleH"},
        {"", ""},
    } // composite literal initilization
    // note the use of := in assigning to cases, that op combines declaration and assignment into one statement
    for _, c := range cases { // range over cases, ignoring the index - the underscore means to discard that return value
        got := Reverse(c.in) // c is the current instance, access in with the familiar dot notation
        if got != c.want { // again, access operator on c, the current instance
            t.Errorf("Reverse(%q) == %q, want %q", c.in, got, c.want) // more access
        }
    }
}

讓我知道是否有幫助。 如果某些陳述仍然沒有意義,我可以嘗試提供更多的口頭摘要或添加更多細節。 另外,如果您不熟悉集合的范圍“范圍”,請參考,返回k, v ,其中k是索引或鍵, v是值。

編輯:有關cases聲明/啟動的詳細信息

    cases := []struct {
        in, want string
    }

第一對大括號內的這一點是結構的定義。 這是一個匿名類型,一個普通的聲明看起來像這樣;

    type case struct {
        in string
        want string
    }

如果你有這樣的東西,那么在這個包的范圍內會有一個名為case的類型(不導出,如果你想讓它“公開”,那么它需要改為type Case )。 相反,示例結構是匿名的。 它與普通類型一樣工作,但是作為開發人員,您將無法引用該類型,因此您實際上只能使用此處初始化的集合。 在內部,此類型與任何其他具有 2 個未導出字段字符串的結構相同。 這些字段命名為inwant 請注意,在此處的賦值中, cases:= []structstruct之前有[]這意味着您要聲明此匿名類型的一部分。

接下來的一點,稱為靜態初始化。 這是將集合初始化為類型的語法。 這些嵌套位(如{"", ""} )中的每一個都是這些匿名結構之一的聲明和初始化,再次由大括號表示。 在這種情況下,您分別將兩個空字符串分配給inwant (如果您不使用名稱,則順序與定義中的順序相同)。 外面一對大括號用於切片。 如果您的切片是 int 或 string 的切片,那么您將只擁有這些值,而無需像myInts:= []int{5,6,7}這樣的額外嵌套級別。

    {
        {"Hello, world", "dlrow ,olleH"},
        {"Hello, 世界", "界世 ,olleH"},
        {"", ""},
    }

去根什么是結構。

你在其中聲明你的變量,這樣你就可以從函數中使用它。 例子:

package main

import (
    "fmt"

)

func main() {
    Get()

}

func Get(){
    out := new(Var)

    out.name = "james"

    fmt.Println(out.name)
}
type Var struct {
    name string
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM