How to define variables in golang

WBOY
Release: 2023-05-11 12:58:38
Original
918 people have browsed it

Go language is a statically typed programming language, so when defining variables, you need to mark their types. In go, we can define variables through the var keyword. Defining a variable requires specifying the variable name and its type.

The following is an example of how golang defines variables:

var a int         // 声明一个名为a的整数型变量
var b string      // 声明一个名为b的字符串型变量
var c float32     // 声明一个名为c的浮点型变量
Copy after login

When defining variables, you can also define multiple variables on the same line and specify their types at the same time:

var a, b int              // 声明两个整数类型变量
var c, d float32          // 声明两个浮点型变量
var name, age, address string  // 声明三个字符串类型变量
Copy after login

Definition When defining a variable, you can also assign an initial value:

var a int = 10            // 定义一个名为a的整数类型变量并初始化为10
var b string = "hello"    // 定义一个名为b的字符串类型变量并初始化为"hello"
var c float32 = 3.14      // 定义一个名为c的浮点型变量并初始化为3.14
Copy after login

When defining a variable, you can also use the short variable declaration method:

a := 10           // 使用短变量声明方式定义一个整数类型变量并初始化为10
b := "hello"      // 使用短变量声明方式定义一个字符串类型变量并初始化为"hello"
c := 3.14         // 使用短变量声明方式定义一个浮点型变量并初始化为3.14
Copy after login

It should be noted that when defining a variable using the short variable declaration method, you must It is used inside the function and cannot be used in the global scope.

In short, in Go language, defining variables is very simple, just use the var keyword. At the same time, it should be noted that when defining a variable, its type must be specified, otherwise the Go language will report an error.

The above is the detailed content of How to define variables in golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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