Golang 基础
来源:互联网 发布:python 中英文混合 编辑:程序博客网 时间:2024/05/24 05:03
包、变量、函数
package mainimport "fmt"func main() { var hello string = "Hello" who := "gopher" var s = hello+"," + who fmt.Println(s)}
包
- 每个 Go 程序都是由包组成的。
- 程序运行的入口是包 main 。
- 按照惯例,包名与导入路径的最后一个目录一致。例如,”math/rand” 包由 package rand 语句开始。
- 不可导入未使用的Import
变量
- 变量声明使用关键字var
- 初始值存在时可省略类型声明
- 短赋值语句:= 可以用于替代 var 的隐式类型声明(:=结构不能使用在函数外,函数外的每个语法块都必须以关键字开始)
- 不能定义未使用的变量
var name1 string //声明变量name1 = "tom" //给变量赋值var name2 string = "tom" //声明变量+赋值var name3 = "tom" // 声明时同时赋值,可以省略变量类型name4 := "tom" //短赋值语句// 多个变量var x, y, z intvar c, python, java boolvar x, y, z int = 1, 2, 3var c, python, java = true, false, "no!"c, python, java := true, false, "no!"
函数
- 可以返回任意数量的返回值
- 类型声明在变量名之后
- 同一类型的多个参数,最后一个参数需声明类型
- 开大括号不能放在单独的一行
func swap(x, y string) (string, string) { return y, x}
- 命名返回值的参数
func split(sum int) (x, y int) { x = sum * 4/9 y = sum - x return}
基本类型
boolstringint int8 int16 int32 int64uint uint8 uint16 uint32 uint64 uintptrbyte // uint8 的别名rune // int32 的别名 // 代表一个Unicode码位float32 float64complex64 complex128
常量
const Pi = 3.14const World = "世界"const Truth = true
运算符
http://www.yiibai.com/go/go_operators.html
注意:
- 没有++i,–i,只有i++、i–
- 不能使用i++、i–对变量直接赋值
流程控制
for
Go 只有一种循环结构—— for 循环
for i := 0; i < 10; i++ { //do something}i := 0for ; i < 1000; { //do something}for i < 1000 { //do something} for { //死循环}
if else
if x < 0 { return x}if v := 0; v < 5 { return v}return 9
switch
case 语句匹配后会自动终止(无需break),除非用 fallthrough 语句作为结尾,则会强制执行下一条case的语句或者default语句,而不判断expression。
x := 2 switch x { case 1: fmt.Println(1) case 2: fmt.Println(2) fallthrough case 3: fmt.Println(x > 1) default: fmt.Println("default") }// 结果// 2// true
defer
延迟(defer)处理
Defer用于确保在稍后的程序中,执行函数调用。
defer语句在封装函数(main)结束时执行。
package mainimport "fmt"import "os"func main() { f := createFile("defer-test.txt") defer closeFile(f) writeFile(f)}func createFile(p string) *os.File { fmt.Println("creating") f, err := os.Create(p) if err != nil { panic(err) } return f}func writeFile(f *os.File) { fmt.Println("writing") fmt.Fprintln(f, "data")}func closeFile(f *os.File) { fmt.Println("closing") f.Close()}// output creating writing closing
复杂类型
struct
要定义结构,必须使用type和struct语句。struct语句定义了一个新的数据类型,在程序中有多个成员。type语句在例子中绑定一个类型为struct的名字。 struct语句的格式如下:
type person struct { name string age int}
访问结构体成员使 .
package mainimport "fmt"type person struct { name string age int}func main() { fmt.Println(person{"Bob", 20}) fmt.Println(person{name: "Alice", age: 30}) fmt.Println(person{name: "Fred"}) fmt.Println(&person{name: "Ann", age: 40}) s := person{name: "Sean", age: 50} fmt.Println(s.name) sp := &s fmt.Println(sp.age) sp.age = 51 fmt.Println(sp.age)}#output{Bob 20}{Alice 30}{Fred 0}&{Ann 40}Sean5051
slice
切片(Slice)是数组上的抽象,提供变长功能的数组。 它实际上使用数组作为底层结构体.len()函数返回切片中存在的元素数量,其中cap()函数返回切片(Slice)的容量(大小),即可容纳多少个元素。
package mainimport "fmt"func main() { var numbers = make([]int,3,5) printSlice(numbers)}func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)}//outputlen=3 cap=5 slice=[0 0 0]
map
var map_variable map[key_data_type]value_data_type
map_variable = make(map[key_data_type]value_data_type)
map_variable := make(map[key_data_type]value_data_type)
delete(map_variable, key)
package mainimport "fmt"func main() { var countryCapitalMap map[string]string = make(map[string]string) /* create a map*/ // countryCapitalMap = make(map[string]string) /* insert key-value pairs in the map*/ countryCapitalMap["France"] = "Paris" countryCapitalMap["Italy"] = "Rome" countryCapitalMap["Japan"] = "Tokyo" countryCapitalMap["India"] = "New Delhi" /* print map using keys*/ for country := range countryCapitalMap { fmt.Println("Capital of", country, "is", countryCapitalMap[country]) } /* test if entry is present in the map or not*/ capital, ok := countryCapitalMap["United States"] /* if ok is true, entry is present otherwise entry is absent*/ if ok { fmt.Println("Capital of United States is", capital) } else { fmt.Println("Capital of United States is not present") } /* delete an entry */ delete(countryCapitalMap, "France") fmt.Println("Entry for France is deleted") fmt.Println("Updated map") /* print map */ for country := range countryCapitalMap { fmt.Println("Capital of", country, "is", countryCapitalMap[country]) }}
range
range 用来遍历array/slice/map
package mainimport "fmt"func main() { nums := []int{2, 3, 4} sum := 0 for _, num := range nums { sum += num } fmt.Println("sum:", sum) for i, num := range nums { if num == 3 { fmt.Println("index:", i) } } kvs := map[string]string{"a": "apple", "b": "banana"} for k, v := range kvs { fmt.Printf("%s -> %s\n", k, v) } for k := range kvs { fmt.Println("key:", k) }}
0 0
- golang基础
- Golang 基础
- Golang学习[基础]
- GoLang学习基础笔记
- Golang基础入门
- golang 并发编程基础
- Golang基础学习总结
- golang基础学习
- golang语言基础篇
- Golang 基础 JSON
- Golang 基础 XML
- Golang 基础 HTTP服务器
- Golang 基础 HTTP请求
- Golang基础学习总结
- Golang--Channel基础
- Golang爬虫基础:目录
- golang 基础语法
- golang基础(1)
- dubbo源码分析-客户端DubboInvoker调用服务端体会Netty的非阻塞IO使用
- 信号卷积
- django搭建个人博客03,编写首页
- 使用Python计算前10000个质数表
- Eclipse快捷键冲突之和系统冲突的快捷键
- Golang 基础
- java.lang.UnsatisfiedLinkError: Couldn’t load locSDK3: findLibrary returned null
- BlueROV-5: Install APM Planner 2 on Rasberry Pi
- 欢迎使用CSDN-markdown编辑器
- 关于Android实现 退出登录那些小事?
- [小技巧] 解决CSDN博客 类别管理/文章分类 批量移动管理问题
- Go方法与并发
- 图解http学习笔记3.HTTP报文内的HTTP信息
- hihoCoder 1081 : 最短路径·一