繼golang第一天后,今天學習下golang的變數、常量、資料型別和控制流陳述句,
做過其他編程語言(比如JavaScript,java,python)專案的話,其實很好理解變數、常量、資料型別和控制流,
變數也被稱為“變數”,是反映事物運動變化狀態的量,比如匯率、房貸利率、貸款利率,
常量也被稱“常數”,是反映事物相對靜止狀態的量,一旦定義,后續不能更改,比如圓周率PI,
Golang是不同于JavaScript和python,但它和java一樣,是一種靜態型別的編程語言,就是說定義變數或常量前需要宣告其型別
1. 變數
1.1 宣告一個變數
變數在使用前需要宣告,例如
package main
import "fmt"
func main() {
var age int //age默認是0
fmt.Printf("我的年齡是:%d 歲\n", age)
age = 99 //給age賦值
fmt.Printf("我的年齡是:%d 歲", age)
}
輸出如圖
?
1.2 自動推導變數型別
也可以用另一種寫法,根據值推導變數的型別
package main
import "fmt"
func main() {
var age = 99
fmt.Printf("我的年齡是:%d 歲\n", age)
age = 100 //
}
輸出結果
?
1.3 速記法定義變數
還有一種更簡潔的寫法
import "fmt"
func main() {
//fmt.Printf("hello, world\n")
//var name string
age := 99
fmt.Printf("我的年齡是:%d 歲\n", age)
age = 100
}
1.4 定義多個變數
真正開發時我們需要定義多個變數,比如一個用戶有姓名,年齡,性別,地址,城市等多個欄位
我是用1.1的寫法定義變數的
package main
import "fmt"
func main() {
//fmt.Printf("hello, world\n")
//var name string
var (
name string = "董廣明"
age int = 99
city string = "金陵城"
)
fmt.Printf("我叫:%s ,年齡:(%d),所在城市:%s", name, age, city)
}
輸出結果
?
1.5 函式式變數
JavaScript中這種定義很常見,一個變數可以是任何型別,包括函式,golang也支持,真是融合了好幾種語言的特性,java并不支持
package main
import "fmt"
func main() {
//變數也可以是函式定義
print := func() {
var (
name string = "董廣明,dgm"
age int = 99
city string = "金陵其實就是南京"
)
fmt.Printf("我叫:%s ,年齡:(%d),所在城市:%s", name, age, city)
}
print()
}
輸出結果
?
2 常量
常量定義和變數類似,只是多了個關鍵字const
package main
import "fmt"
const (
Pi = 3.141592653
Loading = false
Name = "dongguangming"
Age = 99
)
func main() {
const City = "金陵城"
fmt.Println(City)
fmt.Println(Pi)
fmt.Println(Loading)
fmt.Println(Name)
fmt.Println(Age)
//const CompanyName := "某公司" //不支持, 編譯不過去
}
輸出結果
?
常量小結:Constants can only be character, string, boolean, or numeric values and cannot be declared using the := syntax. An untyped constant takes the type needed by its context.
3. 資料型別
分兩種:基本資料型別和derived派生資料型別,在此只先介紹基本的資料型別,后一種以后單獨介紹
3.1 基本資料型別
基本資料型別又有以下幾種型別:布爾bool,字串string,數值型number,復數型資料型別
3.1.1 布爾bool
bool型別表示布爾邏輯,它的值要么為true,要么為false
package main
import "fmt"
func main() {
have := true
nohave := false
fmt.Println("have:", have, "nohave:", nohave)
result_and := have && nohave
fmt.Println("result_and:", result_and)
result_or := have || nohave
fmt.Println("result_or:", result_or)
}
以上代碼中,定義了 變數have并賦值為true和變數nohave并賦值為false
變數result_and被賦值為false,因為邏輯運算子&&表示兩邊的值都為true的情況下才回傳ture,例子中只有have為true,故運算結果為false,
變數result_or被賦值為true,因為邏輯運算子||表示兩邊的值只要有一個為true的情況下就回傳ture了,例子中剛好有have為true,故運算結果為true,
執行以上輸出以下結果
?
理論分析是正確的
3.1.2 字串String型別
字串是位元組的集合,存盤了字符序列,
package main
import (
"fmt"
)
func main() {
first := "董"
last := "廣明"
name := first + last
fmt.Println("我的名字叫: ",name)
}
輸出結果:
?
3.1.3 數值型
數值型細分有以下幾種
Numeric types:
uint either 32 or 64 bits,represents 32 or 64 bit unsigned integers depending on the underlying platform,32 bits in 32 bit systems and 64 bits in 64 bit systems( 0 to 4294967295 in 32 bit systems and 0 to 18446744073709551615 in 64 bit systems ).
int either 32 or 64 bits,represents 32 or 64 bit integers depending on the underlying platform. You should generally be using int to represent integers unless there is a need to use a specific sized integer,32 bits in 32 bit systems and 64 bit in 64 bit systems(-2147483648 to 2147483647 in 32 bit systems and -9223372036854775808 to 9223372036854775807 in 64 bit systems)
uintptr an unsigned integer large enough to store the uninterpreted bits of
a pointer value
uint8 the set of all unsigned 8-bit integers (0 to 255)
uint16 the set of all unsigned 16-bit integers (0 to 65535)
uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
int8 the set of all signed 8-bit integers (-128 to 127)
int16 the set of all signed 16-bit integers (-32768 to 32767)
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64 the set of all signed 64-bit integers
(-9223372036854775808 to 9223372036854775807)
float32 the set of all IEEE-754 32-bit floating-point numbers
float64 the set of all IEEE-754 64-bit floating-point numbers
complex64 the set of all complex numbers with float32 real and imaginary parts
complex128 the set of all complex numbers with float64 real and imaginary parts
byte alias for uint8
rune alias for int32 (represents a Unicode code point)
整數式
package main
import (
"fmt"
"unsafe"
)
func main() {
var first int = 88
second := 99
fmt.Println("第一個值=", first, ",第二個值=", second)
fmt.Printf("first的型別是:%T, first的大小 %d", first, unsafe.Sizeof(first)) //type and size of first
fmt.Printf("\nsecond的型別是: %T, second的大小 %d", second, unsafe.Sizeof(second)) //type and size of second
}

?
浮點數
package main
import (
"fmt"
)
func main() {
first, second := 6.66, 9.99
fmt.Printf("first的型別是 %T second的型別是%T\n", first, second)
sum := first + second
diff := first - second
fmt.Println("相加和是", sum, "相減差是", diff)
}
復數計算
package main
import (
"fmt"
)
func main() {
first := complex(5, 7)
second := 8 + 27i
sum := first + second
fmt.Println("復數相加和:", sum)
diff := first - second
fmt.Println("復數相減差:", diff)
product := first * second
fmt.Println("復數相乘:", product)
}

?
由于數值型可能會引數數學計算,但golang本身沒有自動轉換功能,故需要手工顯示轉換資料型別
package main
import (
"fmt"
)
func main() {
first := 66 //int
second := 77.7 //float64
//sum := first + second //int + float64 not allowed,編譯不通過,故需要下面顯示轉換,golang沒有自動轉換功能
sum := first + int(second) //second is converted to int
fmt.Println(sum)
}
但是有例外情況
package main
import (
"fmt"
)
func main() {
first := 10
var second float64 = float64(first) //this statement will not work without explicit conversion
fmt.Println("second:", second)
}
輸出結果
?
沒有像其他語言轉換后有標志10.0f
4. 流程陳述句
分三種:if條件/if else, loop回圈,switch
4.1 if, if else
4.1.1 if陳述句
用于指定是否應執行相應的代碼塊,語法結構:
if(condition) {
// 執行condition為true時的代碼邏輯
}
例如
=18) {/n/t/tfmt.Printf(/"你已經是成年人了,該掙錢了//n/")/n/t}/n}","classes":[]}" data-cke-widget-upcasted="1" data-cke-widget-keep-attr="0" data-widget="codeSnippet">package main
import "fmt"
func main() {
var country = "中國"
var age = 18
if(country == "中國" && age>=18) {
fmt.Printf("你已經是成年人了,該掙錢了\n")
}
}
輸出結果
?
Note that, You can omit the parentheses () from an if statement in Golang, but the curly braces {} are mandatory -
注意,在golang的世界里你可以不使用if后面的插入語(),但是后面的花括號是必須的,示例
=18 {/n/t/tfmt.Printf(/"你已經是成年人了,該掙錢了//n/")/n}","classes":[]}" data-cke-widget-upcasted="1" data-cke-widget-keep-attr="0" data-widget="codeSnippet">if country == "中國" && age>=18 {
fmt.Printf("你已經是成年人了,該掙錢了\n")
}
4.1.2 If-Else陳述句
一個if陳述句能配合else陳述句塊使用,當if里的條件為false,else陳述句塊的邏輯代碼會被執行,代碼結構
if condition {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
示例代碼
= 18 {/n/t/tfmt.Println(/"很好,你已經是個成年人了,不是小孩子了!!!/")/n/t} else {/n/t/tfmt.Println(/"抱歉,你還未成年!/")/n/t}/n}","classes":[]}" data-cke-widget-upcasted="1" data-cke-widget-keep-attr="0" data-widget="codeSnippet">package main
import "fmt"
func main() {
var age = 18
if age >= 18 {
fmt.Println("很好,你已經是個成年人了,不是小孩子了!!!")
} else {
fmt.Println("抱歉,你還未成年!")
}
}
輸出結果
?
4.1.3 If-Else-If鏈
if陳述句能夠有多個else陳述句塊,例如
=6 && age < 11 {/n/t/tfmt.Println(/"你可能在上小學/");/n/t} else if age >= 12 && age < 15 {/n/t/tfmt.Println(/"你可能在上初中/");/n/t} else if age >= 15 && age < 18 {/n/t/tfmt.Println(/"你可能在上高中/")/n/t} else {/n/t/tfmt.Println(/"上大學了/")/n/t}/n}","classes":[]}" data-cke-widget-upcasted="1" data-cke-widget-keep-attr="0" data-widget="codeSnippet">package main
import "fmt"
func main() {
var age = 12
if age>=6 && age < 11 {
fmt.Println("你可能在上小學");
} else if age >= 12 && age < 15 {
fmt.Println("你可能在上初中");
} else if age >= 15 && age < 18 {
fmt.Println("你可能在上高中")
} else {
fmt.Println("上大學了")
}
}
4.1.4 if短陳述句
if陳述句允許在條件運算式之前包含一個簡短的宣告陳述句
package main
import "fmt"
func main() {
if first := 10; first%2 == 0 {
fmt.Printf("%d 是偶數\n", first)
}
if second := 15; second%2 == 0 {
fmt.Printf("%d 是偶數\n", second)
} else {
fmt.Printf("%d 是奇數\n", second)
}
}
特別留意: The variable declared in the short statement is only available inside the if block and it’s else or else-if branches ,
If you’re using a short statement, then you can’t use parentheses. 如下代碼會報錯
if (second := 15; second%2 == 0) { //語法錯誤不能有()
fmt.Printf("%d 是偶數\n", second)
} else {
fmt.Printf("%d 是奇數\n", second)
}
4.2 回圈Loop
回圈用于重復運行代碼塊,golang 只要一種回圈陳述句l:the for loop,結構如下
for initialization; condition; increment {
// 回圈體
}
初始化陳述句initialization 在回圈的第一次迭代之前執行一次,在每次迭代中,都會檢查條件condition,如果條件的計算結果為true,則執行回圈體,否則,回圈終止,增量陳述句increment 在每次迭代結束時執行,示例代碼:
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
fmt.Printf("%d ", i)
}
}
看,它不需要java一樣需要插入語,
特別注意: for回圈中的initialization和increment陳述句都是可選的,可以省略掉,如下
省略掉初始化陳述句
package main
import "fmt"
func main() {
i := 2
for ; i <= 10; i += 2 {
fmt.Printf("%d ", i)
}
}
省略掉增量陳述句
package main
import "fmt"
func main() {
i := 2
for i <= 20 {
fmt.Printf("%d ", i)
i *= 2
}
}
最后,您還可以從Golang中的for回圈中省略該條件,這將給你一個無限回圈
package main
func main() {
for {
//回圈體陳述句
}
}
終止break陳述句
您可以使用break陳述句在回圈正常終止之前中斷回圈,比如
package main
import "fmt"
func main() {
for num := 1; num <= 50; num++ {
if num%4 == 0 && num%7 == 0 {
fmt.Printf("終止回圈的數: %d\n", num)
break
}
fmt.Printf("未終止回圈的數: %d\n", num)
}
}
輸出
?
continue陳述句
continue陳述句用于中途停止回圈體的運行,并繼續到回圈的下一次迭代,
package main
import "fmt"
func main() {
for num := 1; num <= 10; num++ {
if num%2 == 0 {
continue;
}
fmt.Printf("%d \n", num)
}
}
輸出結果
?
無線回圈infinite loop
語法結構如下
for {
//回圈體
}
package main
import "fmt"
func main() {
for {
fmt.Println("Hello World")
}
}
4.3 Switch
Switch陳述句接受一個運算式,并將其與可能的情況串列相匹配,一旦找到匹配項,它將執行匹配大小寫中指定的代碼塊,
示例代碼
package main
import (
"fmt"
)
func main() {
age := 8
switch age {
case 8:
fmt.Println("小學生")
case 13:
fmt.Println("初中生")
case 17:
fmt.Println("高中生")
case 19:
fmt.Println("大學生")
case 21:
fmt.Println("社會人士")
default: //default case
fmt.Println("小朋友")
}
}
特別注意:
Go從上到下逐一評估所有開關案例,直到案例成功為止, 案例成功后,它將運行該案例中指定的代碼塊,然后停止(不評估其他任何案例),
這與其他語言(例如C,C ++和Java)相反,在C,C ++和Java中,您明確需要在每個案例的主體之后插入break陳述句以停止對后續案例的評估,
如果沒有任何一種情況成功,則執行默認情況,
4.3.1 Switch和簡短的陳述句
就像if一樣,switch也可以在條件運算式之前包含一個簡短的宣告陳述句, 如下
package main
import (
"fmt"
)
func main() {
switch dayOfWeek := 6; dayOfWeek {
case 1:
fmt.Println("星期一")
case 2:
fmt.Println("星期二")
case 3:
fmt.Println("星期三")
case 4:
fmt.Println("星期四")
case 5:
fmt.Println("星期五")
case 6:
{
fmt.Println("星期六")
fmt.Println("周末了哈哈哈!")
}
case 7:
{
fmt.Println("星期天")
fmt.Println("周末了哈哈哈!")
}
default:
fmt.Println("世界末日")
}
}
注意: 唯一的區別是,由簡短陳述句宣告的變數僅在switch塊內部可用,
4.3.2 case情況下多運算式
通過用逗號將多個運算式分隔開,可以包含多個運算式,
package main
import (
"fmt"
)
func main() {
dayOfWeek := "2"
switch dayOfWeek {
case "1", "2", "3", "4", "5": //multiple expressions in case
fmt.Println("上班日")
default:
fmt.Println("休息日")
}
}
4.3.3 沒有運算式的switch
開關中的運算式是可選的,可以省略, 如果省略該運算式,則認為該開關為true,并且評估每個case運算式的真性并執行相應的代碼塊,
= 0 && num <= 50:/n fmt.Println(/"大于等于0且小于等于50/")/n case num >= 51 && num <= 100:/n fmt.Println(/"大于等于50且小于等于100/")/n case num >= 101:/n fmt.Println(/"大于100/")/n }/n}","classes":[]}" data-cke-widget-upcasted="1" data-cke-widget-keep-attr="0" data-widget="codeSnippet">package main
import (
"fmt"
)
func main() {
num := 75
switch { // expression is omitted
case num >= 0 && num <= 50:
fmt.Println("大于等于0且小于等于50")
case num >= 51 && num <= 100:
fmt.Println("大于等于50且小于等于100")
case num >= 101:
fmt.Println("大于100")
}
}
4.3.4型別type switch
switch也可以用來發現介面變數的動態型別, 這種型別開關使用括號內帶有關鍵字type的型別斷言的語法
如果switch在運算式中宣告了變數,則該變數在每個子句中將具有相應的型別, 在這種情況下重用名稱也是慣用的,實際上是在每種情況下宣告一個具有相同名稱但型別不同的新變數,
示例代碼有趣
package main
import (
"fmt"
)
func main() {
var t interface{}
t = 10
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T\n", t) // %T prints whatever type t has
case bool:
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
}
輸出結果
?
4.3.5 組合多個switch case(結合上面的案例4.3.1和4.3.2)
代碼如下
package main
import "fmt"
func main() {
switch dayOfWeek := 5; dayOfWeek {
case 1, 2, 3, 4, 5:
fmt.Println("上班日")
case 6, 7:
fmt.Println("休息")
default:
fmt.Println("世界末日")
}
}
總結: 語言學的知識是相通的,用不到十一就能結束,語法不需要花太多時間學,就好比園區很多碼農(java本身的知識點再加上spring生態圈里的知識點,并沒有全部學完,甚至有的概念都不知道,其實并不影響干活),60%~80%的知識點就夠普通開發了,golang更像是大雜燴,有C的味道,又有JavaScript的口感,看上去有時又像java!!!
參考:
-
What’s the Go language really good for? https://www.infoworld.com/article/3198928/whats-the-go-language-really-good-for.html
-
Golang for loop https://m.youtube.com/watch?feature=youtu.be&v=rO11gboBY3M&fbclid=IwAR0LS6yzU0DksIEkl8neo6pDT31WsmFUwCZoU77RYrcpvcEYhtO22zSCpOs
-
Golang Cheatsheet: Variables https://ado.xyz/blog/golang-cheatsheet-variables/
-
Default Values for Go Types https://ado.xyz/byte/default-values-for-golang-types/
-
Programmering i Go https://unixsheikh.com/programmering-i-go/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/3654.html
標籤:Go
上一篇:Viper決議&加載配置
