6

网络工程师的Golang之路-布尔值、比较运算符、逻辑运算符

 1 year ago
source link: https://www.51cto.com/article/721083.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

网络工程师的Golang之路-布尔值、比较运算符、逻辑运算符

作者:弈心 2022-10-21 16:28:52
同Python一样,Go中布尔值(Boolean)分为true和false,用来判断条件是否成立,唯一的区别是Python中布尔值的首字母为大写(True和False),而Go中则为小写的true和false。讲到布尔值,自然要介绍和它紧密相关的比较运算符和逻辑运算符。

布尔值基本概念

同Python一样,Go中布尔值(Boolean)分为true和false,用来判断条件是否成立,唯一的区别是Python中布尔值的首字母为大写(True和False),而Go中则为小写的true和false。讲到布尔值,自然要介绍和它紧密相关的比较运算符和逻辑运算符。

比较运算符

Go中比较运算符的类型和用法与Python几乎完全相同,它们返回的值都为布尔值,常见的比较运算符(Comparison Operators)如下表所示。

e88e6a94405e6ac05fa0825856490bdd625b4c.jpg

字符、字符串、整数、浮点数都能用比较运算符作比较,举例如下。

package main

import "fmt"

func main() {
 //字符之间做比较
    fmt.Println('P'=='G') 
 //英文字符串之间做比较的话,按首字母按顺序比较,"a"最小,"z"最大,所以"abc" > "bcd"返回false
    fmt.Println("abc" > "bcd") 
 //如果首字母相同,则比较第二、第三个字母,以此类推,这里首字母a一样,因为第二个字母b小于c,所以"ab">"ac"返回false
    fmt.Println("ab">"ac")
 //整数之间做比较
    fmt.Println(100 <= 101)
 //浮点数之间做比较
    fmt.Println(1.1 >= 1.2 )
 //整数和浮点数之间做比较
    fmt.Println(1.0 == 1 )
}
b9cf8901294065bf864642cd53bad004a7e73a.jpg

逻辑运算符

除了比较运算符,使用逻辑运算符(Logical Operators)也能返回布尔值。逻辑运算符有 3 种:与( and )、或(or)、非(not),如下表所示。

b117acd10f081e7a8a652775a588b00b06c0c2.jpg

和Python不同,Go语言中没有and、or、not这几个关键词,取而代之的是&&(and)、II(or)、!(not)这几个符号,举例如下。

package main

import "fmt"

func main() {
 //和(and)运算
    fmt.Println(true && true)
    fmt.Println(true && false)
    fmt.Println(false && true)
    fmt.Println(false && false)
 //与(or)运算
    fmt.Println(true || true)
    fmt.Println(true || false)
    fmt.Println(false || true)
    fmt.Println(false || false)
 //非(not)运算
    fmt.Println(!true)
    fmt.Println(!false)
}
75627d7253d72c4d3b74861304fe4997294145.jpg

注意一点:取非的那个感叹号"!"必须是用英文输入法输入的感叹号"!",用中文输入法输入的感叹号“!”系统会报错。

责任编辑:武晓燕 来源: 今日头条

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK