go笔记.md

linux设置环境变量GOPATH


vim /etc/profile
export GOROOT=/usr/local/go  #设置为go安装的路径,有些安装包会自动设置默认的goroot
export GOPATH=$HOME/gocode   #默认安装包的路径
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
source /etc/profile



cmd 下设置环境变量

window set GOPATH=E:/go_test
linux export GOPATH=E:/go_test

echo %GOPATH%

入口

所有的go程序都是通过main包进入main()方法*

package main
import "fmt"
func main(){
    fmt.Print("Hello world!")
}

打印路径

F:\golang>echo %GOPATH%
E:/go_test        

defer

  • 程序运行结束依然会执行defer

file.Open("file") defer file.Close()

go 异常处理

panic 和Recover

panic

  • 直接抛出异常

recover

  • 可以从异常中恢复过来

函数类型声明

//声明一个函数类型
type sum func(x,y int) int
//申明一个函数
var f sum = func(x,y int) int{
    return x+y
}
fmt.Println(f(3,4))

struct

  • 结构体
  type person struct{
      name  string
      age int
      weight int
  }
  person:=Person{"zhangshan",11 ,33}
  person:=Person{name:"zhangshan",age:11 ,weight:33}
  fmt.Printf("%v",person)

struct 的匿名字段

type Human struct{
    name string
    age int
    weight int
}
type Student struct{
    Human //匿名字段(默认 student 包含Human 的所有字段)
    speciality string
}
Student:=Student{Person{name:"zhangshan",age:11 ,weight:33},"abc"}
fmt.Printf("%v",Student)

GO 面向对象

//定义一个类(结构体) Integer
type Integer struct{
    value int
}
//类中添加成员方法(compare)
func (a Integer) compare(b Integer) bool{
    return a.value < b.value
}
func main(){
     a := Integer{1}
     b := Integer{2}
    fmt.Printf("%v",a.compare(b))
    fmt.Printf("%v",b.compare(b))

}

类初始化

point :=new(Point)
point:=&Point{}
point:=&Point{x:100,y:100}
Point:=Point()


type Point struct{
    px float32
    py float32
}
func (point1 *Point)setxy(px,py float32){
    point1.px = px
    point1.py=py
}
func(point *Point)getxy()(float32,float32 ){
    return point.px , point.py
}
func main(){
    point :=new(Point)
    point.setxy(1.23,4.56)
    px,py:=point.getxy()
    fmt.Print(px,py)
}

面向对象demo

package main

import "fmt"

type  student struct{
    name string
    gender string
    age int
    id int
    score float64
}
func (student *student)say()string{
    infostr := fmt.Sprintf("student 的信息 name = " +
        "[%v] gender = [%v] age = [%v] id=[%v] score = [%v]",
        student.name,student.gender,student.age,student.id,student.score)
    return infostr
}
func main(){
    //测试
    //创建一个student 实例(变量)
    var stu = student{
        name : "som",
        gender:"male",
        age:18,
        id:100,
        //score:1111,
    }
    fmt.Printf(stu.say())
}



type Box struct {
    length float64
    width  float64
    height float64
}
func (box * Box)getvolumn()float64  {
    return box.length * box. width  * box .height
}
func main(){
    var box Box
    box.length = 1.1
    box.width=2.2
    box.height=2.2
    volumn := box.getvolumn()
    fmt.Println(volumn)
    fmt.Printf("体积为 %.2f",volumn) //按照两位小数输出

}

GOLANG工厂模式

多线程协程

func Add(x,y int)  {
    z :=x+y
    fmt.Println(z)
}
func  main()  {
    for i:=1 ;i<10 ; i++{
        go Add(i,i)
    }
    time.Sleep(2)
}

channel

GO语言在语言级别提供的goroutine间的通信方式

channer 的写和读

ch <- c  写
c:=<- ch 读


func Read(ch chan int)  {
    value := <- ch
    fmt.Println("value:" + strconv.Itoa(value))
}
func Write(ch chan  int)  {
    ch <- 10
}
func  main()  {
    ch :=make(chan int)
    go Read(ch)
    go Write(ch)
    time.Sleep(10)
    //value:10
}    


func Add(x,y int ,quit chan int)  {
    z :=x+y
    fmt.Println(z)
    quit <- 1
}
func  main()  {
    chs :=make([]chan int ,10)//chan 接受int 类型的参数 长度为10
    for i:=0;i<10 ;i++  {
        chs [i] = make(chan int)
        go Add(i,i , chs[i])
    }
    //chs 10个数据满了之后就会执行chs
    for  _, v:=range chs{
        <-v
    }
}

windows 下

编译 go build 文件名

编译成指定文件 go build -o myhello.exe hello.go

直接运行运行 go run 文件名

  • linux 下回生成一个可执行文件但是不是.exe

var 和:= 使用


type demo1 struct {
    name string
}
func main() {
    //定义interface{} 类型的时候不需要初始化'='  定义成其他类型需要初始化"="
    var arr =[]string{}   //需要 = 
    var arr3 []string            //不需要 =
    var demo3  demo1        //不需要= 
    var demo2 = demo1{}
    var arr2 []interface{}
    demo3.name="abc"
    arr3re := append(arr3,"abc555")
    re := append(arr,"abc111")
    fmt.Println(re)
    fmt.Println(arr2)
    fmt.Println(demo2)
    fmt.Println(demo3)
    fmt.Println(arr3re)
}

查看各种类型

fmt.Printf("%p %t",v1,v1)

数据类型转换

switch v:=r.(type){
    case mock.Retriever:
        fmt.Println("contents")
    case *real.Retriever:
        fmt.Println("userAgent")
}


1、string到int  

int,err:=strconv.Atoi(string)  

2、string到int64  

int64, err := strconv.ParseInt(string, 10, 64)  

3、int到string  

string:=strconv.Itoa(int)  

4、int64到string  

string:=strconv.FormatInt(int64,10)  

5、字符串到float32/float64

float32, err = ParseFloat(string, 32)  

float64,err = ParseFloat(string,64)

6、int64转int

int:=int(int64)  

7、int转int64

int64:=int64(int)

二、interface{}与其他类型之间的转换

转换方式包括隐式转换与断言转换。

1、interface{}类型转换成具体类型:interfaceVar.(具体类型)

原理:断言实现。如:

断言成功返回true,失败返回false

value, ok := a.(string)
if !ok {
    fmt.Println("It's not ok for type string")
    return
}
fmt.Println("The value is ", value)

2、具体类型可以隐式转换成interface{}类型

3、string与[]byte之间的转换:

string到[]byte:字节数组=[]byte(字符串)


//断言
if v2,ok := v1.(services.User) ; ok{
    v2.Num =v2.Num+1
    this.SetSession("UserInfo",v2)
}else{
    panic("类型错误")
}
Last Updated:
Contributors: 刘荣杰