sm702 发表于 2018-9-20 06:19:30

Golang学习笔记

一、基础

1. Hello World程序
  demo:
  

package main  
import "fmt" // 注释
  
//注释
  
func main() {
  fmt.Printf("Hello World\n")
  
}
  

  执行:
  
go run demo.go
  编译成可执行文件
  
go build demo.go

2. 声明和赋值
  

func main() {  var a int
  var b string = "aaaa"
  var (
  c int
  d bool
  )
  conse i = 10
  e := 15
  a = 1
  b = "hello"
  c = 2
  d = false
  f,g:=12,13
  if (a + c + e < 100 && d) {
  fmt.Printf(&quot;Hello World\n&quot;)
  } else {
  fmt.Printf(b)
  }
  

  
}
  


[*]变量的类型在变量名后面,所以不能同时声明和赋值
[*]在2.4后,支持a:=1这种类型,类似于动态类型的声明了,这时会自动识别变量的类型
[*]可以在var里面声明多个变量
[*]声明了的变量一定要用,不然编译会错误
[*]const定义常量,类似var,而已可以定义多个
字符串转换
  

func main() {  var s string =&quot;aaaaaa&quot;
  sb:=[]byte(s)
  s1:=string(sb)
  fmt.Printf(&quot;%c\n&quot;,sb)
  fmt.Printf(&quot;%s\n&quot;,s1)
  fmt.Printf(&quot;%s\n&quot;,s)
  
}
  

  直接访问字符串的下标是不可以的,需要先转换为byte类型,通过string函数转换回来。
  其他操作符
  Precedence Operator(s)
  
Highest :
  

* / % > & &^  
+ - | ^
  
== != <>=
  
页: [1]
查看完整版本: Golang学习笔记