Variable named struct in go

WBOY
Release: 2024-02-09 08:50:27
forward
618 people have browsed it

go 中名为 struct 的变量

php editor Apple is here to introduce to you the struct variables in the Go language. In the Go language, struct is a custom data type used to encapsulate a set of related data fields. It is similar to a class or structure in other programming languages ​​and can contain fields of various types, such as integers, strings, Boolean values, etc. By defining struct variables, we can easily organize and manage data, making the code clearer and easier to maintain. Whether in web development, system programming or other fields, struct is a very important concept in the Go language and is worthy of our in-depth study and understanding.

Question content

How can I get this output?

type datas struct {
    age int
    height int
    weight int
}
func main(){
    var age := 5
    var height := 10
    var weight := 15
    namelist := []string{"b", "c", "d"}
    for count, a := range namelist {
        a := datas{age+count,height+count,weight+count}
    //Expected Output: b{6,11,16} , c{7,12,17}, d{8,13,18}
    }
}
Copy after login

I can't find any information about this case, I guess this feature is not included. Is there any solution for this situation?

Workaround

Instead, you can use the key names to put the data on the map

type datas struct {
    age int
    height int
    weight int
}
func main(){
    structMap := make(map[string]interface{})
    age := 5
    height := 10
    weight := 15
    namelist := []string{"b", "c", "d"}
    for count, val := range namelist {
        count = count + 1 // this is due to your expected output
        out := datas{age+count,height+count,weight+count}
        structMap[val] = out
    }

    fmt.Println(structMap)
    // output: map[b:{6 11 16} c:{7 12 17} d:{8 13 18}]
}
Copy after login

The above is the detailed content of Variable named struct in go. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!