脚本1: 输出 hello,new gopher!
package main
import “fmt”
func main() {
fmt.Println(“Hello, new gopher!”)
}
脚本2:
package string
func Reverse(s string) string {
b :=[]byte(s)
for i :=0; i< len(b)/2; i++ {
j := len(b)-i-1
b[i],b[j] = b[j],b[i]
}
return string(b)
Go build
脚本3:
package main
import(
“fmt”
“github.com/nf/string”
)
func main() {
fmt.Println(string.Reverse(“Hello, new gopher!”))
}
Defer 语句
Go Playground
Web服务
Package main
Import (
“fmt”
“time”
)
Func main() {
Fmt.Println(“welcome to the go playgorun”)
Fmt.Println(“the time is”, time.Now())
}
ls ~/gocode/bin
~/gocode/bin/time
练习场中的时间始于 2009-11-10 23:00:00 UTC
每个go程序都是由包构成的
程序从main包开始运行
本程序通过导入路径fmt 和 math/rand 来使用者两个包
约定,包名和导入路径的最后一个元素一致
脚本4:
package main
import (
“fmt”
“math/rand”
“time”
)
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("A number from 1-100", rand.Intn(81))
}
Rand.intn() 伪随机函数返回同样的值
Go语言是根据包语言来写
暴露的包首字母为大写
私有的为小写,私有的不能被调用
Fmt math main math/rand 包
脚本5:
package main
import (
“fmt”
“math”
)
func main() {
fmt.Printf(“Now you have %g problems. \n”, math.Sqrt(7))
}
脚本7:
package main
import (
"fmt"
)
func add(x int, y int) int {
return x+y
}
func main() {
fmt.Println(add(42,13))
}