一、Go語言循環
package main
import "fmt"
func main() {
//循環方式1
sum := 0
for i := 1; i <=10; i++{
sum += i
}
fmt.Println(sum)
//循環方式2
sum = 0
//像while循環
for sum<=10 {
sum ++;
}
fmt.Println(sum)
//迭代輸出數組
strs := [2]string{"google", "baidu"}
for i,s := range strs {
//i爲小標,s爲值
fmt.Println(i, s)
}
nums := [6]int{11, 22, 33, 44, 55, 66}
for i, x := range nums {
fmt.Println(i, x)
}
}
二、條件語句
package main
import "fmt"
func main(){
var grade string = "B"
var marks int = 90
switch marks {
case 90: grade = "A"
case 80: grade = "B"
case 50, 60, 70: grade = "C"
default: grade = "D"
}
fmt.Println(grade)
switch{
case grade == "A":
fmt.Println("優秀")
case grade == "B", grade == "C":
fmt.Println("良好")
case grade == "D":
fmt.Println("及格")
case grade == "F":
fmt.Println("不及格")
default:
fmt.Println("差")
}
}
三、函數
package main
import "fmt"
func main() {
var a,b =10,33
//返回多個值
a, b = swap(a,b)
fmt.Println(a, b)
//返回單個值
fmt.Println(max(a,b))
//傳遞引用
swapX(&a, &b)
fmt.Println(a, b);
}
func swap(x, y int) (int, int){
return y,x
}
func max(x, y int) int{
if(x >= y){
return x
}else{
return y
}
}
func swapX(x *int, y *int){
tmp:= *x
*x = *y
*y = tmp
}
四、結構體
package main
import "fmt"
type Book struct{
title string
author string
id int
}
func changeBook(book Book){
book.title = "Java從入門到放棄"
}
func changeBookX(book *Book){
book.title = "Java從入門到放棄"
}
func (book *Book) printBook(){ //爲Book類型綁定printBook的方法,*Book爲指針引用可以修改傳入參數的值
//方法歸屬於類型,不歸屬於具體的對象,聲明該類型的對象即可調用該類型的方法
fmt.Printf("book.title:%s\n", book.title)
fmt.Printf("book.author:%s\n", book.author)
fmt.Printf("book.id:%d\n", book.id)
}
func main(){
var book1 Book
book1.title = "Go從入門到放棄"
book1.author = "張三"
book1.id = 0001
fmt.Println(book1)
//修改title;發現title並沒有被修改
changeBook(book1)
//修改後輸出
fmt.Println(book1)
//修改title;發現title成功修改
changeBookX(&book1)
//修改後輸出
fmt.Println(book1)
book1.printBook();
}