在go语言中,字面量(literal)是用于表达源代码中一个固定值的表示法(notation),也称字面常量;字面量可以被编译器直接转换为某个类型的值。Go的字面量可以出现在两个地方:一是用于常量和变量的初始化,二是用在表达式中作为函数调用实参。Go中的字面量只能表达基本类型的值,Go不支持用户自定义字面量。
本教程操作环境:windows7系统、GO 1.18版本、Dell G3电脑。
字面量是什么
编程语言源程序中表示固定值的符号叫做字面量,也称字面常量。一般使用裸字符序列来表示不同类型的值。字面量可以被编程语言编译器直接转换为某个类型的值。Go的字面量可以出现在两个地方:一是用于常量和变量的初始化,二是用在表达式中作为函数调用实参。变量初始化语句中如果没有显式地指定变量类型,则Go编译器会结合字面量的值自动进行类型推断。Go中的字面量只能表达基本类型的值,Go不支持用户自定义字面量。
字面量类型
整型字面量
整型字面量使用特定的字符序列表示具体的整型数值。常用于整型变量或常量的初始化。例如:
42 0X6F
浮点型字面量
浮点型字面量使用特定字符序列来表示一个浮点数值。它支持两种格式:一种是标准的数学小数形式,例如0.23;另一种是科学计数法,例如1E6。
3.61 // 数学小数形式 3E2 // 科学计数法
复数类型字面量
复数类型字面量使用特定的字符序列来表示复数类型的常量值。
0i 011i 0.i 2.123i 1.e+0i 5.123-11i .25i
字符型字面量
Go的源码采用UTF-8的编码方式,UTF-8字符占用1~4个字节。Go的字符采用一对单引号包裹。
'a' '本' '\n' '\000' '\x0f' '\u12e4'
字符串字面量
Go中的字符串字面量表现形式是采用一对双引号或一对"`"包裹的字符字面量或其编码值。
"\n" "\"" `"` "Hi, Golang!" "今天天气不错"
字面量和变量有啥区别
先看一段代码
func foo() string { return "yif" } func main() { bar := foo() fmt.Println(&bar) //0xc00003c1f0 }
如果使用下面代码就报错:
func foo() string { return "yif" } func main() { fmt.Println(&foo()) //cannot take the address of foo() }
为什么先用变量名承接一下再取地址就不会报错,而直接使用在函数返回后的值上取地址就不行呢?
这是因为,如果不使用一个变量名承接一下,函数返回的是一个字符串的文本值,也就是字符串字面量,而这种基本类型的字面量是不可寻址的。
要想使用 &
进行寻址,就必须得用变量名承接一下。
什么是组合字面量
首先看下Go文档中对组合字面量(Composite Literal)的定义:
Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated. They consist of the type of the literal followed by a brace-bound list of elements. Each element may optionally be preceded by a corresponding key。
翻译成中文大致如下:组合字面量是为结构体、数组、切片和map构造值,并且每次都会创建新值。它们由字面量的类型后紧跟大括号及元素列表。每个元素前面可以选择性的带一个相关key。
什么意思呢?所谓的组合字面量其实就是把对象的定义和初始化放在一起了。
接下来让我们看看结构体、数组、切片和map各自的常规方式和组合字面量方式。
结构体的定义和初始化
常规方式
常规方式这样定义是逐一字段赋值,这样就比较繁琐
func main() { // 声明对象 var p person // 属性赋值 p.name = "yif" p.age = 20 } type person struct { name string age int }
组合字面量方式
func main() { // 声明 + 属性赋值 p := person{ name: "yif", age: 20, } fmt.Println(p) } type person struct { name string age int }
数组的定义和初始化
常规方式
一个一个的给元素赋值。即数组变量的定义和初始化是分开的
func main() { var nameArr [3]string nameArr[0] = "yif" nameArr[1] = "tom" nameArr[2] = "jim" fmt.Println(nameArr) }
组合字面量方式
该示例中,就是将变量nameArr的定义和初始化合并了在一起
func main() { nameArr := [3]string{"yif", "tom", "jim"} fmt.Println(nameArr) }
slice的定义和初始化
常规方式
func main() { // 第一种 var s []string //定义切片变量s,s为默认零值nil s = append(s, "hat", "shirt") //往s中增加元素 fmt.Println(s) // 第二种 s2 := make([]string, 0, 10) //定义s,s的默认值不为零值 fmt.Println(s2) }
组合字面量方式
由上面的常规方式可知,首先都是需要先定义切片,然后再往切片中添加元素。接下来我们看下组合字面量方式。
func main() { s := []string{"yif", "tom"} //定义和初始化一步完成,自动计算切片的容量和长度 fmt.Println(s) }
map的定义和初始化
常规方式
func main() { //通过make函数初始化 m := make(map[string]int, 10) m["english"] = 99 m["math"] = 98 fmt.Println(m) }
组合字面量方式
func main() { m := map[string]int{ "english": 99, "math": 98, } fmt.Println(m) }
字面量的寻址问题
字面量,说白了就是未命名的常量,跟常量一样,他是不可寻址的。
这边以数组字面量为例进行说明
func foo() [3]int { return [3]int{1, 2, 3} } func main() { fmt.Println(&foo()) // cannot take the address of foo() }
The above is the detailed content of What are literals in go language?. For more information, please follow other related articles on the PHP Chinese website!

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)