go语言变量 转常量_go中的变量和常量

go语言变量 转常量

In the last few articles, we have been talking about Go data types on an abstract level. Today we will see them in action.As mentioned before, Go is a statically typed language which means that the specification of the variable’s data type at its creation is mandatory.

在最近的几篇文章中,我们一直在抽象地讨论Go数据类型。 今天,我们将看到它们的运行。如前所述,Go是一种静态类型的语言,这意味着在创建变量时必须对变量的数据类型进行规范。

Go gives us flexibility on how to specify a variable’s scope. Want to learn more about scopes? Refer to this article. For programmers who have used any statically typed language like C, C++, java etc. will find the structure of the variable declaration in Go backward.

Go使我们可以灵活地指定变量的范围。 想更多地了解范围? 请参阅本文 。 对于使用过任何静态类型语言(例如C,C ++,java等)的程序员,可以在Go backward中找到变量声明的结构。

var age int8
var name string
var isAdmin bool

yaaay🎊🎊 you have just declared your first variable in GO.

yaaay🎊🎊,您刚刚在GO中声明了您的第一个变量。

The var keyword tells the Go compiler that the value of age can change at any point in time throughout the life of the program. age is the name given to the allocated slot in memory. int8 is the data type. Confused about what a data type is? Read this article.

var关键字告诉Go编译器,age的值可以在程序的整个生命周期中的任何时间点改变。 age是分配给内存中已分配插槽的名称。 int8是数据类型。 对什么是数据类型感到困惑? 阅读本文

But again, if one knows in advanced the value to be stored, why type // var age int8 = 19? Well, Go provides us with a shorthand declaration.

但是再一次,如果预先知道要存储的值,为什么键入// var age int8 = 19 ? 好吧,Go为我们提供了一个简短的声明。

age := 19
name := "tado"

Wait, but you said that when declaring a variable in Go, the data type must be specified. Where is it🤔🤔? At compile time, the Go compiler will infer the data type from the value being assigned. Use this form only if and only if the data to be stored is known at declaration time.

等等,但是您说过,在Go中声明变量时,必须指定数据类型。 在哪里? 在编译时,Go编译器将从分配的值中推断出数据类型。 仅当且仅当声明时知道要存储的数据时,才使用此表格。

What about arrays, slices, maps or Struts?

数组,切片,地图或Struts呢?

Arrays

数组

Arrays also follow the same structure as the primitive types.

数组也遵循与原始类型相同的结构。

// var variableName type
// array declarationvar ages [3]int8// 2D array
var unitStudents [3][20]int

In the above declaration, we are telling Go to create for us three contiguous memory slots to hold int8(bytes) data. The downside with arrays in Go is that we have to specify the number of memory slots to be created at declaration time.

在上面的声明中,我们告诉Go为我们创建三个连续的内存插槽,以容纳int8(bytes)数据。 Go中数组的缺点是我们必须指定在声明时要创建的内存插槽数。

Indicies are used to add or retrieve elements from an array. Note that in Computer science indices count starts from 0 up to n-1 where n is the number of slots to be created.

索引用于添加或检索数组中的元素。 请注意,在计算机科学索引中,计数从0到n-1开始,其中n是要创建的插槽数

ages[0] = 18
ages[1] = 19
ages[2] = 20// will throw an index out of the bound error
ages[3] = 21// if you know the number of values
// you can use this notation
theirNames := [...]string{"Luke", "Tado", "Twist", "Stephanie"}// to retrieve a value from the array
// indices are again used
fmt.Println(ages[0]) // output: 18

practice with arrays.

与数组一起练习。

Slices

切片

Declaring slices is a bit different from arrays. There are two ways of achieving that. One way is declaration + initialization, and the other is through the make() function which takes the data type as the first argument, the length of the slice as the second argument and the capacity as the size that the underlying array will have.

声明分片与数组有点不同。 有两种方法可以实现这一目标。 一种方法是声明 + 初始化,另一种方法是通过make()函数,该函数将数据类型作为第一个参数,将片的长度作为第二个参数,将容量作为基础数组将具有的大小。

 // declaration + initialization
ages := []int{18, 19, 20, 21}// using the make(type, len, cap) function
names:= make([]string, 5, 10)// slices from arrays
myArray := [...]int{10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
sliceFromArray1 := myArray[:4] // output: [10, 11, 12, 13]
sliceFromArray2 := myArray[5:7] // output: [15, 16]

Be careful when passing slices around because modifications to the copy are reflected in the original too, and this is because they are all sharing the same memory address or rather the same underlying array.

传递切片时要小心,因为对副本的修改也反映在原始副本中,这是因为它们都共享相同的内存地址或相同的基础数组。

babyNames := []string{"Charlotte", "Aiden", "Owen", "Alexander"}
fmt.Println(babyNames) // output: [Charlotte Aiden Owen Alexander]babyNamesCopy := babyNames
babyNamesCopy[0] = "Amelia"fmt.Println(babyNamesCopy) // [Amelia Aiden Owen Alexander]
fmt.Println(babyNames) // [Amelia Aiden Owen Alexander]

practice with slices.

用切片练习

Maps

地图

Enough of indices, let’s look at maps. In Go, a map is a key => value pair data structure that allows us to store data against some known keys for faster retrieval. Any primitive Go data type can be used to play the role of a key in a map.

索引足够多,让我们看看地图。 在Go中,映射是一个键=>值对数据结构,该结构允许我们针对一些已知键存储数据以加快检索速度。 任何原始的Go数据类型均可用于在地图中扮演键的角色。

// the syntax is like map[key-type]value-typetop4AfricanCountriesPopulation := map[string]int32{
"Nigeria": 206139589,
"Ethiopia": 114963588,
"Egypt": 102334404,
"DR Congo": 89561403,
}// print the population of DR Congo
fmt.Println(top4AfricanCountriesPopulation["DR Congo"])
// output: 89561403

One thing to note though about the retrieval of data from a map is that if a key does not exist, the Go compiler will not consider that as an error because by design the Go compiler expects those kinds of things to occur. Another example would be when reading from a file if the supplied file does not exist, it will not flag that as an error. Alternatively, Go returns a flag alongside the value from the map, using which you can test if a key exists.

但是,从映射中检索数据时要注意的一件事是,如果不存在键,则Go编译器不会将其视为错误,因为Go编译器设计时希望发生这种情况。 另一个示例是,如果提供的文件不存在,则从文件读取时,它不会将其标记为错误。 另外,Go会在地图中的值旁边返回一个标志,您可以使用该标志测试键是否存在。

// using our African population map
// let's try to retrieve Kenya's populationfmt.Println(top4AfricanCountriesPopulation["Kenya"])
// output: 0
// by default Go gives a zero value to non-initialized variables// let's use the flag to determine if a value exist in the map
key := "Kenya"
_, flag := top4AfricanCountriesPopulation[key]fmt.Printf("does the key %v exist? %v", key, flag)

Practice with maps.

练习地图。

Structs

结构

A struct is a grouping of related variables under one data structure. For more information, read this article.

结构是一个数据结构下一组相关变量的组合。 有关更多信息,请阅读本文

// How to create a struct
type Person struct{
FirstName string
LastName string
Age int8
Hobbies []string
}// How to use a struct
tado := Person{
FirstName: "twist",
LastName: "tado",
Age: 19,
Hobbies: []string{"coding", "writing", "playing football"},
}// How to retrieve data from a struct
fmt.Println(tado.Age)

Go allows us to create anonymous structs. They are useful when you want to create a one-time usable structure. It is a mix of declaration and initialization, plus they can be used just like any other struct.

Go允许我们创建匿名结构。 当您要创建一次性可用结构时,它们很有用。 它是声明和初始化的组合,并且它们可以像其他任何结构一样使用。

// anonymous struct
doctorJuly := struct{ name string} { name: "Juliette"}// Print the doctor's name
fmt.Println(doctorJuly.name)

practice with struct.

与结构一起练习。

奖金 (Bonus)

In Go, the way you name your variables matters a lot not just because it is case insensitive but also because if you start a variable name with an uppercase example Name:= “Micheal”, the Go compiler will make it available for use by any piece of code under the same package.

在Go中,变量的命名方式非常重要,不仅因为它不区分大小写,而且还因为如果您以大写示例Name:=“ Micheal”开头的变量名,Go编译器将使其可供任何人使用同一包下的一段代码。

Go does not allow you to create a variable then not use it anywhere in the code, it will throw an error if it finds an unused variable in the code.

Go不允许您创建变量,然后在代码中的任何地方都不使用它,如果在代码中找到未使用的变量,它将引发错误。

常数 (Constants)

constants are inverse of variables. While variables can change after the declaration, constants remain the same throughout the life of the whole program. The value of a constant must be determined at compile time otherwise the Go compiler will throw an error.

常数是变量的倒数。 尽管变量可以在声明后更改,但常量在整个程序的生命周期中都保持不变。 必须在编译时确定常量的值,否则Go编译器将引发错误。

Unlike variables, constants cannot use the := expression. The const is used instead of var.

与变量不同,常量不能使用:=表达式。 使用const代替var。

const Pi = 3.14// this will throw an error
// because the Sqrt(4) cannot be determined at
// compile time
const sqrt4 = math.Sqrt(4)

结论 (Conclusion)

We have seen how to declare variables using both primitives and collection data types. Do not forget, the naming of variables matters a lot as mentioned in the Bonus section. Constants are used to represent values that will not change thought out the life of the program. #HappyReading

我们已经看到了如何使用原语和集合数据类型声明变量。 别忘了,变量的命名非常重要,如“奖金”部分所述。 常量用于表示在程序生命周期内不会改变的值。 #HappyReading

翻译自: https://medium.com/@twisttado/variables-and-constants-in-go-42c5a3ca60c7

go语言变量 转常量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值