go语言变量 转常量_如何在Go中使用变量和常量

go语言变量 转常量

Variables are an important programming concept to master. They are symbols that stand in for a value you’re using in a program.

变量是要掌握的重要编程概念。 它们是代表您在程序中使用的值的符号。

This tutorial will cover some variable basics and best practices for using them within the Go programs you create.

本教程将介绍一些可变的基础知识以及在您创建的Go程序中使用它们的最佳实践。

了解变量 (Understanding Variables)

In technical terms, a variable is assigning a storage location to a value that is tied to a symbolic name or identifier. We use the variable name to reference that stored value within a computer program.

用技术术语来说,变量是将存储位置分配给与符号名称或标识符绑定的值。 我们使用变量名来引用计算机程序中存储的值。

We can think of a variable as a label that has a name on it, which you tie onto a value.

我们可以将变量视为带有名称的标签,并将其绑定到值上。

Let’s say we have an integer, 1032049348, and we want to store it in a variable rather than continuously retype the long number over and over again. To achieve this, we can use a name that’s easy to remember, like the variable i. To store a value in a variable, we use the following syntax:

假设我们有一个整数1032049348 ,我们想将其存储在变量中,而不是一遍又一遍地连续重新输入长整数。 为此,我们可以使用易于记忆的名称,例如变量i 。 要将值存储在变量中,我们使用以下语法:

i := 1032049348

We can think of this variable like a label that is tied to the value.

我们可以将此变量视为与值绑定的标签。

The label has the variable name i written on it, and is tied to the integer value 1032049348.

标签上写有变量名i ,并与整数值1032049348

The phrase i := 1032049348 is a declaration and assignment statement that consists of a few parts:

短语i := 1032049348是一个声明和赋值语句,由以下几部分组成:

  • the variable name (i)

    变量名( i )

  • the short variable declaration assignment (:=)

    简短的变量声明赋值( := )

  • the value that is being tied to the variable name (1032049348)

    绑定到变量名称的值( 1032049348 )

  • the data type inferred by Go (int)

    Go( int )推断的数据类型

    the data type inferred by Go (int)

    Go( int )推断的数据类型

We’ll see later how to explicitly set the type in the next section.

我们将在下一节中看到如何显式设置类型。

Together, these parts make up the statement that sets the variable i equal to the value of the integer 1032049348.

这些部分共同构成了将变量i设置为等于整数1032049348

As soon as we set a variable equal to a value, we initialize or create that variable. Once we have done that, we are ready to use the variable instead of the value.

一旦我们将变量设置为等于值,就可以初始化或创建该变量。 完成此操作后,就可以使用变量而不是值了。

Once we’ve set i equal to the value of 1032049348, we can use i in the place of the integer, so let’s print it out:

一旦将i设置为1032049348的值,就可以使用i代替整数,因此我们将其打印出来:

package main

import "fmt"

func main() {
    i := 1032049348
    fmt.Println(i)
}

   
   
     
     
     
     
Output
1032049348

We can also quickly and easily do math by using variables. With i := 1032049348, we can subtract the integer value 813 with the following syntax:

我们还可以使用变量快速轻松地进行数学运算。 使用i := 1032049348 ,我们可以使用以下语法减去整数值813

fmt.Println(i - 813)

   
   
     
     
     
     
Output
1032048535

In this example, Go does the math for us, subtracting 813 from the variable i to return the sum 1032048535.

在此示例中,Go为我们进行了数学运算,从变量i减去813以返回总和1032048535

Speaking of math, variables can be set equal to the result of a math equation. You can also add two numbers together and store the value of the sum into the variable x:

说到数学,可以将变量设置为等于数学方程式的结果。 您还可以将两个数字加在一起并将和的值存储到变量x

x := 76 + 145

You may have noticed that this example looks similar to algebra. In the same way that we use letters and other symbols to represent numbers and quantities within formulas and equations, variables are symbolic names that represent the value of a data type. For correct Go syntax, you’ll need to make sure that your variable is on the left side of any equations.

您可能已经注意到,该示例看起来与代数相似。 与使用字母和其他符号表示公式和方程式中的数字和数量相同,变量是表示数据类型值的符号名称。 对于正确的Go语法,您需要确保变量在任何方程式的左侧。

Let’s go ahead and print x:

让我们继续打印x

package main

import "fmt"

func main() {
    x := 76 + 145
    fmt.Println(x)
}

   
   
     
     
     
     
Output
221

Go returned the value 221 because the variable x was set equal to the sum of 76 and 145.

Go返回值221因为变量x设置为等于76145之和。

Variables can represent any data type, not just integers:

变量可以代表任何数据类型,而不仅仅是整数:

s := "Hello, World!"
f := 45.06
b := 5 > 9 // A Boolean value will return either true or false
array := [4]string{"item_1", "item_2", "item_3", "item_4"}
slice := []string{"one", "two", "three"}
m := map[string]string{"letter": "g", "number": "seven", "symbol": "&"}

If you print any of these variables, Go will return what that variable is equivalent to. Let’s work with the assignment statement for the string slice data type:

如果您打印这些变量中的任何一个,Go将返回该变量等效的内容。 让我们使用字符串slice数据类型的赋值语句:

package main

import "fmt"

func main() {
    slice := []string{"one", "two", "three"}
    fmt.Println(slice)
}

   
   
     
     
     
     
Output
[one two three]

We assigned the slice value of []string{"one", "two", "three"} to the variable slice, and then used the fmt.Println function to print out that value by calling slice.

我们将[]string{"one", "two", "three"}的切片值分配给变量slice ,然后使用fmt.Println函数通过调用slice来打印出该值。

Variables work by carving out a little area of memory within your computer that accepts specified values that are then associated with that space.

变量的工作方式是在计算机中切出一小部分内存,该内存接受指定的值,然后再与该空间关联。

声明变量 (Declaring Variables)

In Go, there are several ways to declare a variable, and in some cases, more than one way to declare the exact same variable and value.

在Go中,有多种方法来声明变量,在某些情况下,还有不止一种方法来声明完全相同的变量和值。

We can declare a variable called i of data type int without initialization. This means we will declare a space to put a value, but not give it an initial value:

我们可以声明一个名为i的数据类型为int的变量,而无需初始化。 这意味着我们将声明一个空间来放置一个值,但不给它一个初始值:

var i int

This creates a variable declared as i of data type int.

这将创建一个声明为i的数据类型为int的变量。

We can initialize the value by using the equal (=) operator, like in the following example:

我们可以使用equal( = )运算符来初始化值,如以下示例所示:

var i int = 1

In Go, both of these forms of declaration are called long variable declarations.

在Go中,这两种声明形式都称为long变量声明

We can also use short variable declaration:

我们还可以使用短变量声明

i := 1

In this case, we have a variable called i, and a data type of int. When we don’t specify a data type, Go will infer the data type.

在这种情况下,我们有一个名为i的变量和一个int数据类型。 当我们不指定数据类型时,Go会推断出该数据类型。

With the three ways to declare variables, the Go community has adopted the following idioms:

通过三种声明变量的方式,Go社区采用了以下习语:

  • Only use long form, var i int, when you’re not initializing the variable.

    当您不初始化变量时,仅使用长格式var i int

  • Use short form, i := 1, when declaring and initializing.

    在声明和初始化时,请使用缩写i := 1

  • If you did not desire Go to infer your data type, but you still want to use short variable declaration, you can wrap your value in your desired type, with the following syntax:

    如果您不希望使用Go来推断数据类型,但仍想使用简短的变量声明,则可以使用以下语法将值包装在所需的类型中:

i := int64(1)

It’s not considered idiomatic in Go to use the long variable declaration form when we’re initializing the value:

在我们初始化值时,在Go中不认为使用长变量声明形式是惯用的:

var i int = 1

It’s good practice to follow how the Go community typically declares variables so that others can seamlessly read your programs.

遵循Go社区通常如何声明变量,以便其他人可以无缝读取您的程序是一个好习惯。

零值 (Zero Values)

All built-in types have a zero value. Any allocated variable is usable even if it never has a value assigned. We can see the zero values for the following types:

所有内置类型的值均为零。 任何分配的变量都可以使用,即使它从未分配任何值。 我们可以看到以下类型的零值:

package main

import "fmt"

func main() {
    var a int
    var b string
    var c float64
    var d bool

    fmt.Printf("var a %T = %+v\n", a, a)
    fmt.Printf("var b %T = %q\n", b, b)
    fmt.Printf("var c %T = %+v\n", c, c)
    fmt.Printf("var d %T = %+v\n\n", d, d)
}

   
   
     
     
     
     
Output
var a int = 0 var b string = "" var c float64 = 0 var d bool = false

We used the %T verb in the fmt.Printf statement. This tells the function to print the data type for the variable.

我们在fmt.Printf语句中使用了%T动词。 这告诉函数打印变量的data type

In Go, because all values have a zero value, we can’t have undefined values like some other languages. For instance, a boolean in some languages could be undefined, true, or false, which allows for three states to the variable. In Go, we can’t have more than two states for a boolean value.

在Go语言中,因为所有值都zero ,所以不能像其他语言一样具有undefined值。 例如,某些语言中的boolean可以是undefinedtruefalse ,这允许该变量具有three状态。 在Go中,布尔值的状态不能超过two

命名变量:规则和样式 (Naming Variables: Rules and Style)

The naming of variables is quite flexible, but there are some rules to keep in mind:

变量的命名非常灵活,但是需要牢记一些规则:

  • Variable names must only be one word (as in no spaces).

    变量名只能是一个单词(不能有空格)。
  • Variable names must be made up of only letters, numbers, and underscores (_).

    变量名称只能由字母,数字和下划线( _ )组成。

  • Variable names cannot begin with a number.

    变量名不能以数字开头。

Following these rules, let’s look at both valid and invalid variable names:

遵循这些规则,让我们看一下有效和无效的变量名称:

Valid Invalid Why Invalid
userName user-name Hyphens are not permitted
name4 4name Cannot begin with a number
user $user Cannot use symbols
userName user name Cannot be more than one word
有效 无效 为什么无效
userName user-name 不允许使用连字符
name4 4name 不能以数字开头
user $user 不能使用符号
userName user name 不能超过一个字

Furthermore, keep in mind when naming variables that they are case sensitive. These names userName, USERNAME, UserName, and uSERnAME are all completely different variables. It’s best practice to avoid using similar variable names within a program to ensure that both you and your collaborators—current and future—can keep your variables straight.

此外,在命名变量时,请记住它们区分大小写。 这些名称userNameUSERNAMEUserNameuSERnAME都是完全不同的变量。 最佳实践是避免在程序中使用相似的变量名称,以确保您和您的合作者(当前和将来)都可以使变量保持直线。

While variables are case sensitive, the case of the first letter of a variable has special meaning in Go. If a variable starts with an uppercase letter, then that variable is accessible outside the package it was declared in (or exported). If a variable starts with a lowercase letter, then it is only available within the package it is declared in.

尽管变量区分大小写,但是变量的首字母的大小写在Go中具有特殊含义。 如果变量以大写字母开头,则可以在声明(或exported )的包外部访问该变量。 如果变量以小写字母开头,那么它仅在声明它的包中可用。

var Email string
var password string

Email starts with an uppercase letter and can be accessed by other packages. password starts with a lowercase letter, and is only accessible inside the package it is declared in.

Email以大写字母开头,并且可以被其他软件包访问。 password以小写字母开头,并且只能在声明其的包中访问。

It is common in Go to use very terse (or short) variable names. Given the choice between using userName and user for a variable, it would be idiomatic to choose user.

在Go中使用非常简洁(或简短)的变量名是很常见的。 给定在使用userNameuser作为变量之间的选择, userName选择user

Scope also plays a role in the terseness of the variable name. The rule is that the smaller the scope the variable exists in, the smaller the variable name:

范围在变量名的简洁性中也起作用。 规则是变量存在的范围越小,变量名称就越小:

names := []string{"Mary", "John", "Bob", "Anna"}
for i, n := range names {
    fmt.Printf("index: %d = %q\n", i, n)
}

We use the variable names in a larger scope, so it would be common to give it a more meaningful name to help remember what it means in the program. However, we use the i and n variables immediately in the next line of code, and then do not use them again.. Because of this, it won’t confuse someone reading the code about where the variables are used, or what they mean.

我们在更大的范围内使用变量names ,因此通常给它一个更有意义的名称以帮助记住程序中的含义。 但是,我们在下一行代码中立即使用了in变量,然后不再使用它们。因此,这不会使阅读代码的人混淆变量的使用位置或含义。 。

Next, let’s cover some notes about variable style. The style is to use MixedCaps or mixedCaps rather than underscores for multi-word names.

接下来,让我们涵盖有关变量样式的一些注意事项。 样式是使用MixedCapsmixedCaps而不是下划线表示多字名称。

Conventional Style Unconventional Style Why Unconventional
userName user_name Underscores are not conventional
i index prefer i over index as it is shorter
serveHTTP serveHttp acronyms should be capitalized
传统风格 非常规风格 为什么非常规
userName user_name 下划线不是常规的
i index index更喜欢i ,因为它更短
serveHTTP serveHttp 首字母缩写词应大写

The most important thing about style is to be consistent, and that the team you work on agrees to the style.

关于样式的最重要的事情是保持一致,并且您工作的团队同意样式。

重新分配变量 (Reassigning Variables)

As the word “variable” implies, we can change Go variables readily. This means that we can connect a different value with a previously assigned variable through reassignment. Being able to reassign is useful because throughout the course of a program we may need to accept user-generated values into already initialized variables. We may also need to change the assignment to something previously defined.

正如“变量”一词所暗示的,我们可以随时更改Go变量。 这意味着我们可以通过重新分配将不同的值与先前分配的变量连接。 能够重新分配很有用,因为在程序的整个过程中,我们可能需要将用户生成的值接受到已初始化的变量中。 我们可能还需要将分配更改为先前定义的内容。

Knowing that we can readily reassign a variable can be useful when working on a large program that someone else wrote, and it isn’t clear what variables are already defined.

在其他人编写的大型程序上工作时,知道我们可以轻松地重新分配变量可能很有用,而且尚不清楚已定义了哪些变量。

Let’s assign the value of 76 to a variable called i of type int, then assign it a new value of 42:

让我们将值76分配给名为int类型的i的变量,然后为其分配新值42

package main

import "fmt"

func main() {
    i := 76
    fmt.Println(i)

    i = 42
    fmt.Println(i)
}

   
   
     
     
     
     
Output
76 42

This example shows that we can first assign the variable i with the value of an integer, and then reassign the variable i assigning it this time with the value of 42.

这个例子表明,我们可以首先分配可变i与的整数的值,然后重新分配变量i给它分配这次的值42

Note: When you declare and initialize a variable, you can use :=, however, when you want to simply change the value of an already declared variable, you only need to use the equal operator (=).

注意:在声明初始化变量时,可以使用:= ,但是,当您只想更改已声明的变量的值时,只需使用等号运算符( = )。

Because Go is a typed language, we can’t assign one type to another. For instance, we can’t assign the value "Sammy" to a variable of type int:

因为Go是一种typed语言,所以我们不能将一种类型分配给另一种。 例如,我们不能将值"Sammy"分配给int类型的变量:

i := 72
i = "Sammy"

Trying to assign different types to each other will result in a compile-time error:

尝试彼此分配不同的类型将导致编译时错误:


   
   
     
     
     
     
Output
cannot use "Sammy" (type string) as type int in assignment

Go will not allow us to use a variable name more than once:

Go不允许我们多次使用变量名:

var s string
var s string

   
   
     
     
     
     
Output
s redeclared in this block

If we try to use short variable declaration more than once for the same variable name we’ll also receive a compilation error. This can happen by mistake, so understanding what the error message means is helpful:

如果我们尝试对相同的变量名称多次使用短变量声明,则会收到编译错误。 这可能是错误发生的,因此了解错误消息的含义是有帮助的:

i := 5
i := 10

   
   
     
     
     
     
Output
no new variables on left side of :=

Similarly to variable declaration, giving consideration to the naming of your variables will improve the readability of your program for you, and others, when you revisit it in the future.

与变量声明类似,在以后再次访问时,考虑变量的命名将提高程序对您和他人的可读性。

多重分配 (Multiple Assignment)

Go also allows us to assign several values to several variables within the same line. Each of these values can be of a different data type:

Go还允许我们为同一行中的多个变量分配多个值。 这些值中的每一个可以具有不同的数据类型:

j, k, l := "shark", 2.05, 15
fmt.Println(j)
fmt.Println(k)
fmt.Println(l)

   
   
     
     
     
     
Output
shark 2.05 15

In this example, the variable j was assigned to the string "shark", the variable k was assigned to the float 2.05, and the variable l was assigned to the integer 15.

在此示例中,变量j被分配给字符串"shark" ,变量k被分配给float 2.05 ,变量l被分配给整数15

This approach to assigning multiple variables to multiple values in one line can keep the number of lines in your code down. However, it’s important to not compromise readability for fewer lines of code.

这种在一行中将多个变量分配给多个值的方法可以减少代码中的行数。 但是,重要的是,不要牺牲更少的代码行的可读性。

全局和局部变量 (Global and Local Variables)

When using variables within a program, it is important to keep variable scope in mind. A variable’s scope refers to the particular places it is accessible from within the code of a given program. This is to say that not all variables are accessible from all parts of a given program—some variables will be global and some will be local.

在程序中使用变量时,记住变量范围很重要。 变量的范围是指可以从给定程序的代码中访问的特定位置。 这就是说,并不是所有变量都可以从给定程序的所有部分访问,有些变量是全局变量,有些是局部变量。

Global variables exist outside of functions. Local variables exist within functions.

全局变量存在于函数之外。 局部变量存在于函数中。

Let’s take a look at global and local variables in action:

让我们看看实际的全局和局部变量:

package main

import "fmt"


var g = "global"

func printLocal() {
    l := "local"
    fmt.Println(l)
}

func main() {
    printLocal()
    fmt.Println(g)
}

   
   
     
     
     
     
Output
local global

Here we use var g = "global" to create a global variable outside of the function. Then we define the function printLocal(). Inside of the function a local variable called l is assigned and then printed out. The program ends by calling printLocal() and then printing the global variable g.

在这里,我们使用var g = "global"在函数外部创建全局变量。 然后,我们定义函数printLocal() 。 在函数内部分配了一个名为l的局部变量,然后将其打印出来。 该程序通过调用printLocal()结束,然后打印全局变量g

Because g is a global variable, we can refer to it in printLocal(). Let’s modify the previous program to do that:

因为g是全局变量,所以我们可以在printLocal()引用它。 让我们修改以前的程序来做到这一点:

package main

import "fmt"


var g = "global"

func printLocal() {
    l := "local"
    fmt.Println(l)
    fmt.Println(g)
}

func main() {
    printLocal()
    fmt.Println(g)
}

   
   
     
     
     
     
Output
local global global

We start by declaring a global variable g, var g = "global". In the main function, we call the function printLocal, which declares a local variable l and prints it out, fmt.Println(l). Then, printLocal prints out the global variable g, fmt.Println(g). Even though g wasn’t defined within printLocal, it could still be accessed because it was declared in a global scope. Finally, the main function prints out g as well.

我们首先声明一个全局变量gvar g = "global" 。 在main函数中,我们调用函数printLocal ,该函数声明一个局部变量l并将其打印输出fmt.Println(l) 。 然后, printLocal打印出全局变量gfmt.Println(g) 。 即使未在printLocal定义g ,仍可以访问它,因为它是在全局范围内声明的。 最后, main功能也会打印出g

Now let’s try to call the local variable outside of the function:

现在,让我们尝试在函数外部调用局部变量:

package main

import "fmt"

var g = "global"

func printLocal() {
    l := "local"
    fmt.Println(l)
}

func main() {
    fmt.Println(l)
}

   
   
     
     
     
     
Output
undefined: l

We can’t use a local variable outside of the function it is assigned in. If you try to do so, you’ll receive a undefined error when you compile.

我们不能在分配了该函数的函数之外使用局部变量。如果尝试这样做,那么在编译时会收到undefined错误。

Let’s look at another example where we use the same variable name for a global variable and a local variable:

让我们看另一个例子,我们为全局变量和局部变量使用相同的变量名:

package main

import "fmt"

var num1 = 5

func printNumbers() {
    num1 := 10
    num2 := 7  

    fmt.Println(num1)
    fmt.Println(num2)
}

func main() {
    printNumbers()
    fmt.Println(num1)
}

   
   
     
     
     
     
Output
10 7 5

In this program, we declared the num1 variable twice. First, we declared num1 at the global scope, var num1 = 5, and again within the local scope of the printNumbers function, num1 := 10. When we print num1 from the main program, we see the value of 5 printed out. This is because main only sees the global variable declaration. However, when we print out num1 from the printNumbers function, it sees the local declaration, and will print out the value of 10. Even though printNumbers creates a new variable called num1 and assigned it a value of 10, it does not affect the global instance of num1 with the value of 5.

在此程序中,我们两次声明了num1变量。 首先,我们在全局范围var num1 = 5声明num1 ,然后在printNumbers函数num1 := 10的局部范围内声明num1 。 当从main打印num1 ,我们看到了5的值。 这是因为main仅看到全局变量声明。 但是,当我们从printNumbers函数中打印出num1时,它将看到本地声明,并将打印出值10 。 即使printNumbers创建了一个新的名为num1变量并将其赋值为10 ,它也不会影响值为5num1全局实例。

When working with variables, you also need to consider what parts of your program will need access to each variables; adopting a global or local variable accordingly. Across Go programs, you’ll find that local variables are typically more common.

在使用变量时,还需要考虑程序的哪些部分需要访问每个变量。 相应地采用全局或局部变量。 在Go程序中,您会发现局部变量通常更常见。

常数 (Constants)

Constants are like variables, except they can’t be modified once they have been declared. Constants are useful for defining a value that will be used more than once in your program, but shouldn’t be able to change.

常量就像变量一样,只不过它们一旦声明就无法修改。 常量对于定义将在程序中多次使用但不能更改的值很有用。

For instance, if we wanted to declare the tax rate for a shopping cart system, we could use a constant and then calculate tax in different areas of our program. At some point in the future, if the tax rate changes, we only have to change that value in one spot in our program. If we used a variable, it is possible that we might accidentally change the value somewhere in our program, which would result in an improper calculation.

例如,如果我们要声明购物车系统的税率,则可以使用一个常数,然后在程序的不同区域中计算税率。 在将来的某个时刻,如果税率发生变化,我们只需要在程序中的一个位置更改该值即可。 如果使用变量,则可能会意外地在程序中的某个位置更改该值,这将导致计算不正确。

To declare a constant, we can use the following syntax:

要声明一个常量,我们可以使用以下语法:

const shark = "Sammy"
fmt.Println(shark)

   
   
     
     
     
     
Output
Sammy

If we try to modify a constant after it was declared, we’ll get a compile-time error:

如果在声明常量后尝试修改常量,则会出现编译时错误:


   
   
     
     
     
     
Output
cannot assign to shark

Constants can be untyped. This can be useful when working with numbers such as integer-type data. If the constant is untyped, it is explicitly converted, where typed constants are not. Let’s see how we can use constants:

常量可以是untyped 。 在处理数字(例如整数类型的数据)时,这很有用。 如果常量是untyped ,则将其进行显式转换,而typed常量则不是。 让我们看看如何使用常量:

package main

import "fmt"

const (
    year     = 365
    leapYear = int32(366)
)

func main() {
    hours := 24
    minutes := int32(60)
    fmt.Println(hours * year)    
    fmt.Println(minutes * year)   
    fmt.Println(minutes * leapYear)
}

   
   
     
     
     
     
Output
8760 21900 21960

If you declare a constant with a type, it will be that exact type. Here when we declare the constant leapYear, we define it as data type int32. Therefore it is a typed constant, which means it can only operate with int32 data types. The year constant we declare with no type, so it is considered untyped. Because of this, you can use it with any integer data type.

如果用类型声明常量,则该类型将是该类型。 在这里,当我们声明常数leapYear ,我们将其定义为数据类型int32 。 因此,它是一个typed常量,这意味着它只能与int32数据类型一起使用。 我们声明的year常量没有类型,因此将其视为未untyped 。 因此,您可以将其与任何整数数据类型一起使用。

When hours was defined, it inferred that it was of type int because we did not explicitly give it a type, hours := 24. When we declared minutes, we explicitly declared it as an int32, minutes := int32(60).

定义hours后,可以推断出它的类型为int因为我们没有明确给它指定类型, hours := 24 。 当我们声明minutes ,我们将其显式声明为int32minutes := int32(60)

Now let’s walk through each calculation and why it works:

现在,让我们看一下每个计算及其工作原理:

hours * year

In this case, hours is an int, and years is untyped. When the program compiles, it explicitly converts years to an int, which allows the multiplication operation to succeed.

在这种情况下, hours是一个int ,而years是未键入的 。 程序编译时,将把years显式转换为int ,从而使乘法运算成功。

minutes * year

In this case, minutes is an int32, and year is untyped. When the program compiles, it explicitly converts years to an int32, which allows the multiplication operation to succeed.

在这种情况下, minutes是一个int32 ,而year是未键入的 。 程序编译时,会将years显式转换为int32 ,从而使乘法运算成功。

minutes * leapYear

In this case, minutes is an int32, and leapYear is a typed constant of int32. There is nothing for the compiler to do this time as both variables are already of the same type.

在这种情况下, minutes是一个int32 ,而leapYear是一个类型int32常量。 编译器这次没有任何操作,因为两个变量已经是同一类型。

If we try to multiply two types that are typed and not compatible, the program will not compile:

如果我们试图在被多重两种typed和不兼容,程序将无法编译:

fmt.Println(hours * leapYear)

   
   
     
     
     
     
Output
invalid operation: hours * leapYear (mismatched types int and int32)

In this case, hours was inferred as an int, and leapYear was explicitly declared as an int32. Because Go is a typed language, an int and an int32 are not compatible for mathematical operations. To multiply them, you would need to convert one to a int32 or an int.

在这种情况下, hours被推断为int ,而leapYear被明确声明为int32 。 因为Go是一种类型化的语言,所以intint32与数学运算不兼容。 要乘以它们,您需要将其转换为int32int

结论 (Conclusion)

In this tutorial we reviewed some of the common use cases of variables within Go. Variables are an important building block of programming, serving as symbols that stand in for the value of a data type we use in a program.

在本教程中,我们回顾了Go中变量的一些常见用法。 变量是编程的重要组成部分,用作表示我们在程序中使用的数据类型的值的符号。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-use-variables-and-constants-in-go

go语言变量 转常量

你可能感兴趣的:(python,java,c++,编程语言,go)