golang學習筆記——基礎知識(1)

觀看B站李文周老師的視頻學習golang整理的筆記

 
變量
  • 定義
var 變量名 變量類型
  • 多個
var(
    a  int
    b  int
)
  • 自動識別變量類型運算符「:=」
a := 10
  • 匿名變量符「_」
a,_,c := 1,2,3 //其中2將不會被賦值
  • 定義類型別名
type 別名 類型  //type cjp int32  須要再main函數外面爲類型定義別名
 
常亮
  • 定義
const 常量名 = 值
  • 定義多個常亮
const{
    a = 10
    b = 20
}
  • iota的使用
const{
    a = iota  // a = 0
    b = iota  // b = 1
}
//當 iota 遇到const時 被重置爲0
const a = iota //a = 0
const b = iota //b = 0
 
字符串
  • 獲取字符串長度
str := "hello world"
fmt.printf("str length is %d" , len(str))  //str length is 11
  • 訪問單個字符
str := "hello world"
fmt.printf("str[0] is %c",str[0]) //str[0] is h
 
從鍵盤獲取值
fmt.Scan(&a)
 
條件語句
  • switch語句【 switch默認至關於每一個case最後帶有break,匹配成功後不會自動向下執行其餘case,而是跳出整個switch, 可是可使用fallthrough強制執行後面的case代碼,fallthrough不會判斷下一條case的expr結果是否爲true
var a int = 2
switch {
case a == 2:
         fmt.Print("aaaaaa")
         fallthrough
case a < 1:
         fmt.Print("bbbbbb")
         fallthrough
case a == 3:
         fmt.Print("cccccc")
}
//輸出 aaaaaabbbbbbcccccc
  • for語句
for i := 10; i < 20; i++ {
    fmt.Print("asdasa")
}
 
//使用range關鍵字
str := "hello world"
for k, v := range str {
         fmt.Printf("str[%d] is %c \n", k, v)
}
  • if語句
if a := 10;a < 20{
    fmt.Println("a的值小於20")
}
相關文章
相關標籤/搜索