Demo
1.Hello World
package main
//注意空行
import "fmt"
//注意空行
func main(){
fmt.Println("Hello,world")
}
2.Module Import
国内可能无法访问go包代理网站,换个镜像
go env -w GOPROXY=https://goproxy.cn
代码如下
package main
import "fmt"
import "rsc.io/quote"
func main(){
fmt.Println(quote.Go())
}
先go mod init hello
,生成go.mod文件
然后 go run hello.go
,得到输出如下
go: finding module for package rsc.io/quote
go: downloading rsc.io/quote v1.5.2
go: found rsc.io/quote in rsc.io/quote v1.5.2
go: downloading rsc.io/sampler v1.3.0
go: downloading golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c
Hello,world
Don't communicate by sharing memory, share memory by communicating.
环境变量
Go tools expect a certain layout of the source code. GOROOT and GOPATH are environment variables that define this layout.
GOROOT
GOROOT is a variable that defines where your Go SDK is located. You do not need to change this variable, unless you plan to use different Go versions.
GOPATH
GOPATH is a variable that defines the root of your workspace. By default, the workspace directory is a directory that is named go within your user home directory (~/go for Linux and MacOS, %USERPROFILE%/go for Windows).
基本语法
命令行go操作
go build hello.go # 生成可执行文件
go run hello.go # 直接运行go程序
variable & const
普通变量声明
var identifier1, identifier2 [type] = value1,value2
//注意,在go里,declared but not use是会在编译期报错的
identifier := value
//注意,:=左侧必须含有新变量
export variable
// capital letter --> exported variable
pi := math.Pi
// can only use exported variable
// ./prog.go:9:14: cannot refer to unexported name math.pi
pi := math.pi
type conversion
In go, type conversion must be explicit
However, type inference is OK when defining a new variable
常量声明
加上const关键字即可 const identifier [type] = value
也可以做枚举:
const (
Unknown = 0
Female = 1
Male = 2
)
array
var a [2]string
a[0] = "Hello"
a[1] = "World"
//var := [num]type{初始化列表,逗号分隔}
primes := [6]int{
2, 3, 5, 7, 11, 13}
//切片不包含右边,且切片并没有复制原数组
var s []int = primes[1:4]
use make to create dynamic-sized array
//make([]type, len, cap)
b :=