[go语言入门day_1 | 青训营笔记]

64 阅读3分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 1 天

什么是go语言?

1.高性能、高并发
2.语法简单、学习曲线平缓
3.丰富的标准库
4.完善的工具链
5.静态链接
6.快速编译
7.跨平台
8.垃圾回收

哪些公司在使用go?

image.png

字节跳动为什么使用go?

1.最初使用的是python,由于性能问题换成了go
2.c++不太适合在线web业务
3.早期团队不是爪哇背景
4.性能较好
5.部署简单、学习成本低
6.内部rpc和http框架的推广

go的基础语法

变量

var 变量名 变量类型 赋值-> var 变量名 变量类型 = 值
省略类型:var 变量名 变量类型=值
省略var:直接使用:=的方式(只能在函数内使用) demo := 24

if else

if a>b{

}else { }

循环

go语言中只有for循环
使用breakcontinue 跳出或继续

switch

a :=2
switch a{
case 1:
fmt.prinf
case 2:
fmt.prinf
default
fmt.prinf

}

数组

var a[5]int a[0]=1 或者 var b=[5]int{1,2,3,4,5}

切片

 这一块还不是很理解,暂且理解为List集合类型吧
 使用make
 s :=make([]string,1)
 s[0]="a"
 s=append(s,"d")

map

  同样也是使用make
  m := make(map[string]int)
  m["one"]=1
  m["two"]=2

函数

func 函数名(形参 类型)返回值{ return }

结构体

type 结构体名字 struct{ 变量名 类型 }

错误处理

使用err 同时也是使用if来判断 不需要抛出异常

字符串操作

image.png

go实战小项目

猜谜游戏

一个非常经典的ifelse猜谜游戏 使用rand函数生成一些随机数,然后通过scanf输入值,在使用ifelse来判断你输入的值是否等于生成的值。最后加入for循环,如果你猜不到就一直进入循环,直到你输入的值与生成的随机数相等时循环结束。

在线字典

使用go发送http请求到翻译引擎,最后声明结构体来接受json数据并且解析json数据,最后将json数据打印出来。

package main

import (
   "bytes"
   "encoding/json"
   "fmt"
   "io/ioutil"
   "log"
   "net/http"
   "os"
)

type DictRequest struct {
   TransType string `json:"trans_type"`
   Source    string `json:"source"`
   UserID    string `json:"user_id"`
}
type DictResponse struct {
   Rc   int `json:"rc"`
   Wiki struct {
      KnownInLaguages int `json:"known_in_laguages"`
      Description     struct {
         Source string      `json:"source"`
         Target interface{} `json:"target"`
      } `json:"description"`
      ID   string `json:"id"`
      Item struct {
         Source string `json:"source"`
         Target string `json:"target"`
      } `json:"item"`
      ImageURL  string `json:"image_url"`
      IsSubject string `json:"is_subject"`
      Sitelink  string `json:"sitelink"`
   } `json:"wiki"`
   Dictionary struct {
      Prons struct {
         EnUs string `json:"en-us"`
         En   string `json:"en"`
      } `json:"prons"`
      Explanations []string      `json:"explanations"`
      Synonym      []string      `json:"synonym"`
      Antonym      []interface{} `json:"antonym"`
      WqxExample   [][]string    `json:"wqx_example"`
      Entry        string        `json:"entry"`
      Type         string        `json:"type"`
      Related      []interface{} `json:"related"`
      Source       string        `json:"source"`
   } `json:"dictionary"`
}

func main() {
   if len(os.Args) != 2 {
      fmt.Fprintf(os.Stderr, `usage:simpleDict WORD example:simpleDict hello`)
      os.Exit(1)
   }
   word := os.Args[1]
   query(word)
}

func query(word string) {
   client := &http.Client{}
   //var data = strings.NewReader(`{"trans_type":"en2zh","source":"hello"}`)
   request := DictRequest{TransType: "en2zh", Source: word}
   buf, err := json.Marshal(request)
   if err != nil {
      log.Fatal(err)
   }  
   var data = bytes.NewReader(buf)
   req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)
   if err != nil {
      log.Fatal(err)
   }
   req.Header.Set("authority", "api.interpreter.caiyunai.com")
   req.Header.Set("accept", "application/json, text/plain, */*")
   req.Header.Set("accept-language", "zh-CN,zh;q=0.9")
   req.Header.Set("app-name", "xy")
   req.Header.Set("content-type", "application/json;charset=UTF-8")
   req.Header.Set("device-id", "")
   req.Header.Set("origin", "https://fanyi.caiyunapp.com")
   req.Header.Set("os-type", "web")
   req.Header.Set("os-version", "")
   req.Header.Set("referer", "https://fanyi.caiyunapp.com/")
   req.Header.Set("sec-ch-ua", `"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"`)
   req.Header.Set("sec-ch-ua-mobile", "?0")
   req.Header.Set("sec-ch-ua-platform", `"Windows"`)
   req.Header.Set("sec-fetch-dest", "empty")
   req.Header.Set("sec-fetch-mode", "cors")
   req.Header.Set("sec-fetch-site", "cross-site")
   req.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36")
   req.Header.Set("x-authorization", "token:qgemv4jr1y38jyq6vhvi")
   resp, err := client.Do(req)
   if err != nil {
      log.Fatal(err)
   }
   defer resp.Body.Close()
   bodyText, err := ioutil.ReadAll(resp.Body)
   if err != nil {
      log.Fatal(err)
   }
   //fmt.Printf("%s\n", bodyText)
   var dictresponse DictResponse
   err = json.Unmarshal(bodyText, &dictresponse)
   if err != nil {
      log.Fatal(err)
   }
   //fmt.Println("%#v\n",dictresponse)
   for _, item := range dictresponse.Dictionary.Explanations {
      fmt.Println(item)
   }
}