go语言入门小结

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 := 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值