1. 程式人生 > 實用技巧 >go語言的基礎語法

go語言的基礎語法

字串陣列

package main

import (
	"fmt"
)

func main() {
	var str string
	str = "hello world"
	ch := str[0]
	fmt.Printf("the length of\"%s\" is %d \n", str, len(str))
	fmt.Println("the first character of\"%s\"is %c.\n", str, ch)
}

基本變數

package main

import (
	"fmt"
)

func main() {
	/*變數使用
	var v1, v2, v3 int
	var v4, v5 bool
	v1, v2, v3 = 10, 20, 30
	v4, v5 = true, false
	fmt.Println(v1, v2, v3, v4, v5)
	fmt.Println("Hello World!")
	v4, v5 = v5, v4
	v1, v2, v3 = v3, v1, v2//賦值變數交換,不限數量
	fmt.Println(v1, v2, v3, v4, v5)
	v6 := 100//省略var宣告的定義賦值 :=
	fmt.Println(v6)
	*/
	/*常量使用
	const N = 100
	const MAX_SIZE = 10
	fmt.Println(N, MAX_SIZE)
	const School = "China West Normal University"
	fmt.Println(School)
	*/
	/*位元組切片轉換字串
	s := "hello"
	c := []byte(s) // 將字串 s 轉換為 []byte 型別
	c[0] = 'c'
	c[3] = 'c'
	s2 := string(c) // 再轉換回 string 型別
	fmt.Printf("%s\n", s2)
	*/
	/*指標陣列
	a, b, c := 10, 20, 30
	var arr [3]*int//定義的是陣列存地址
	arr[0] = &a
	arr[1] = &b
	arr[2] = &c
	for i := 0; i < 3; i++ {
		fmt.Printf("%5d", *arr[i])//引用陣列地址指向的值
	}
	*/
	/*陣列作為函式引數
	func main() {
		x := [5]int{1, 2, 3, 4, 5}
		f(x, true)
		f(x, false)
	}
	func f(a [5]int, b bool) {
		for i := 0; i < len(a); i++ {
			if b {
				a[i] += 10
			}
			fmt.Printf("%5d", a[i])
		}
		fmt.Println()
	}
	*/
	/*map定義並賦初值
	dict := map[string]int{"abc": 12, "bcd": 100, "chen": 200}
	//var 字典名 map[型別1]型別2   ,其中型別1為索引型別,型別2為存放的資料型別。
	for x, y := range dict {
		fmt.Println(x, y)
	}
	*/

}

陣列

package main

import (
	"fmt"
)

func main() {

	array := [5]int{1, 2, 3, 4, 5}
	fmt.Println("Hello World!")
	for i := 0; i < len(array); i++ {
		fmt.Println("element", i, "of array is", array[i])
	}
}

多變數賦值

package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello World!")
	var i int32
	var j int64

	i, j = 1, 2
	/*if i == j {
		fmt.Println("i and j are equal.")

	}*/
	if i == 1 || j == 2 {
		fmt.Println("i and j are equal.")
	}
}