7 天学个Go,Go 结构体 + Go range 来学学

写在学习前

在前一篇博客我们学习了 Go 数组,其要求所有元素为同一数据类型,如果希望存储不同类型的数据,就要用到结构体相关知识。

结构定义:存储相同或不同类型的数据集。

[En]

Definition of structure: stores the same or different types of data sets.

有 C 相关经验,结构体还是比较容易理解的,语法格式如下所示:

type struct_variable_type struct {
   member definition
   member definition
   ...

   member definition
}

上述语法格式的关键字是 structtypestruct_variable_type 是结构体名称,例如我们声明一个【人】的结构体,有姓名,有年龄,有性别。

package main

import "fmt"

// 声明结构体
type People struct {
    name string
    age  int
    sex  int
}

func main() {
    //使用结构体
    people := People{
        "橡皮擦",
        18,
        0}
    fmt.Println(people)
}

在写作时,应注意语法格式,建议将结构代码的使用放在一行中,或在最后一个元素后面加上右大括号。

[En]

When writing, you should pay attention to the grammatical format, in which the use of the structure code is recommended to be placed on one line, or the right curly braces follow the last element.

您还可以使用结构来携带元素名称,其编写方式如下。

[En]

You can also use a structure to carry an element name, which is written as follows.

//使用结构体
people := People{name: "橡皮擦", age: 18, sex: 0}
fmt.Println(people)

访问结构体成员 使用 结构体.成员名 即可,当然也可以用该办法进行赋值。

//使用结构体
var people1 People
// var people2 People

people1.name = "橡皮擦"
people1.age = 18
people1.sex = 1

fmt.Println(people1)

Go Range

作为一个 Python 程序员,关键字 range 是非常熟悉的,在 Go 中 range 关键字可以用于 for 循环,用于数组它返回元素的索引和值,在后续学习的集合中返回键值对。

range 用于数组的语法格式如下所示:

for i,value := range a_array{
    // TODO
}

结合语法格式,编写以下代码:

[En]

Combined with the syntax format, write the following code:

package main

import "fmt"

var a_array = []int{1, 2, 3, 4, 5, 6, 7, 8}

func main() {
    for i, value := range a_array {
        fmt.Printf("索引:%d,值:%d\n", i, value)
    }
}

运行代码输出如下信息:

索引:0,值:1
索引:1,值:2
索引:2,值:3
索引:3,值:4
索引:4,值:5
索引:5,值:6
索引:6,值:7
索引:7,值:8

如果将 range 作用于字符串,可以对其每个字符进行迭代输出。

package main

import (
    "fmt"
)

func main() {
    var str string = "xiangpica"
    for k, v := range str {
        fmt.Println(k, string(v))
    }
}

上述 str 中的内容为纯英文, k 值每次+1。

0 x
1 i
2 a
3 n
4 g
5 p
6 i
7 c
8 a

如果 str 中包含中文, k 值每次 +3,代码如下:

func main() {
    var str string = "橡皮擦"
    for k, v := range str {
        fmt.Println(k, string(v))
    }
}

输出结果如下:

0 橡
3 皮
6 擦

如果是中文和英文的混合,结果会更有趣。

[En]

If it is a mixture of Chinese and English, the result will be more interesting.

0 x
1 i
2 a
3 n
4 g
5 橡
8 p
9 i
10 皮
13 c
14 a
15 擦

这里其实可以得到一个结论, range 迭代是的 Unicode,而不是字节,返回值是 UTF-8 编码第 1 个字节的索引,所以索引值有可能并不连续。

在编写代码时,如果不需要索引并且只保留元素,则可以使用废弃占位符,如下所示:

[En]

When writing code, if you do not need an index and only retain elements, you can use obsolete placeholders as follows:

var str string = "xiang橡pi皮ca擦"
for _, v := range str {
    fmt.Println(string(v))
}

Original: https://blog.51cto.com/cnca/5574838
Author: 梦想橡皮擦
Title: 7 天学个Go,Go 结构体 + Go range 来学学

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/500791/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球