Table of Contents
字面量是什么
字面量和变量有啥区别
什么是组合字面量
结构体的定义和初始化
数组的定义和初始化
slice的定义和初始化
map的定义和初始化
字面量的寻址问题
Home Backend Development Golang What are literals in go language?

What are literals in go language?

Dec 28, 2022 am 11:25 AM
golang go language

在go语言中,字面量(literal)是用于表达源代码中一个固定值的表示法(notation),也称字面常量;字面量可以被编译器直接转换为某个类型的值。Go的字面量可以出现在两个地方:一是用于常量和变量的初始化,二是用在表达式中作为函数调用实参。Go中的字面量只能表达基本类型的值,Go不支持用户自定义字面量。

What are literals in go language?

本教程操作环境:windows7系统、GO 1.18版本、Dell G3电脑。

字面量是什么

编程语言源程序中表示固定值的符号叫做字面量,也称字面常量。一般使用裸字符序列来表示不同类型的值。字面量可以被编程语言编译器直接转换为某个类型的值。Go的字面量可以出现在两个地方:一是用于常量和变量的初始化,二是用在表达式中作为函数调用实参。变量初始化语句中如果没有显式地指定变量类型,则Go编译器会结合字面量的值自动进行类型推断。Go中的字面量只能表达基本类型的值,Go不支持用户自定义字面量。

字面量类型

  • 整型字面量

整型字面量使用特定的字符序列表示具体的整型数值。常用于整型变量或常量的初始化。例如:

42
0X6F
Copy after login
  • 浮点型字面量

浮点型字面量使用特定字符序列来表示一个浮点数值。它支持两种格式:一种是标准的数学小数形式,例如0.23;另一种是科学计数法,例如1E6。

3.61 // 数学小数形式
3E2 // 科学计数法
Copy after login
  • 复数类型字面量

复数类型字面量使用特定的字符序列来表示复数类型的常量值。

0i
011i
0.i
2.123i
1.e+0i
5.123-11i
.25i
Copy after login
  • 字符型字面量

Go的源码采用UTF-8的编码方式,UTF-8字符占用1~4个字节。Go的字符采用一对单引号包裹。

'a'
'本'
'\n'
'\000'
'\x0f'
'\u12e4'
Copy after login
  • 字符串字面量

Go中的字符串字面量表现形式是采用一对双引号或一对"`"包裹的字符字面量或其编码值。

"\n"
"\""
`"`
"Hi, Golang!"
"今天天气不错"
Copy after login

字面量和变量有啥区别

先看一段代码

func foo() string {
	return "yif"
}

func main() {
	bar := foo()
	fmt.Println(&bar) //0xc00003c1f0
}
Copy after login

如果使用下面代码就报错:

func foo() string {
	return "yif"
}

func main() {
	fmt.Println(&foo()) //cannot take the address of foo()
}
Copy after login

为什么先用变量名承接一下再取地址就不会报错,而直接使用在函数返回后的值上取地址就不行呢?

这是因为,如果不使用一个变量名承接一下,函数返回的是一个字符串的文本值,也就是字符串字面量,而这种基本类型的字面量是不可寻址的。

要想使用 & 进行寻址,就必须得用变量名承接一下。

什么是组合字面量

首先看下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
}
Copy after login

组合字面量方式

func main() {
	// 声明 + 属性赋值
	p := person{
		name: "yif",
		age:  20,
	}
	fmt.Println(p)
}

type person struct {
	name string
	age  int
}
Copy after login

数组的定义和初始化

常规方式

一个一个的给元素赋值。即数组变量的定义和初始化是分开的

func main() {
	var nameArr [3]string
	nameArr[0] = "yif"
	nameArr[1] = "tom"
	nameArr[2] = "jim"
	fmt.Println(nameArr)
}
Copy after login

组合字面量方式

该示例中,就是将变量nameArr的定义和初始化合并了在一起

func main() {
	nameArr := [3]string{"yif", "tom", "jim"}
	fmt.Println(nameArr)
}
Copy after login

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)
}
Copy after login

组合字面量方式

由上面的常规方式可知,首先都是需要先定义切片,然后再往切片中添加元素。接下来我们看下组合字面量方式。

func main() {
	s := []string{"yif", "tom"} //定义和初始化一步完成,自动计算切片的容量和长度
	fmt.Println(s)
}
Copy after login

map的定义和初始化

常规方式

func main() {
	//通过make函数初始化
	m := make(map[string]int, 10)
	m["english"] = 99
	m["math"] = 98
	fmt.Println(m)
}
Copy after login

组合字面量方式

func main() {
	m := map[string]int{
		"english": 99,
		"math":    98,
	}
	fmt.Println(m)
}
Copy after login

字面量的寻址问题

字面量,说白了就是未命名的常量,跟常量一样,他是不可寻址的。

这边以数组字面量为例进行说明

func foo() [3]int {
	return [3]int{1, 2, 3}
}

func main() {
	fmt.Println(&foo()) // cannot take the address of foo()
}
Copy after login

【相关推荐:Go视频教程编程教学

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

How to solve the problem of Golang generic function type constraints being automatically deleted in VSCode? How to solve the problem of Golang generic function type constraints being automatically deleted in VSCode? Apr 02, 2025 pm 02:15 PM

Automatic deletion of Golang generic function type constraints in VSCode Users may encounter a strange problem when writing Golang code using VSCode. when...

How to ensure concurrency is safe and efficient when writing multi-process logs? How to ensure concurrency is safe and efficient when writing multi-process logs? Apr 02, 2025 pm 03:51 PM

Efficiently handle concurrency security issues in multi-process log writing. Multiple processes write the same log file at the same time. How to ensure concurrency is safe and efficient? This is a...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to use Golang to implement Caddy-like background running, stop and reload functions? How to use Golang to implement Caddy-like background running, stop and reload functions? Apr 02, 2025 pm 02:12 PM

How to implement background running, stopping and reloading functions in Golang? During the programming process, we often need to implement background operation and stop...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

See all articles