Golang语法、技巧和窍门

在这里插入图片描述

Golang简介

  • 命令式语言
  • 静态类型
  • 语法标记类似于C(但括号较少且没有分号),结构类似Oberon-2
  • 编译为本机代码(没有JVM)
  • 没有类,但有带有方法的结构
  • 接口
  • 没有实现继承。不过有type嵌入。
  • 函数是一等公民
  • 函数可以返回多个值
  • 支持闭包
  • 指针,但没有指针算术
  • 内置并发原语:Goroutines和Channels

基本语法

你好,世界

文件 hello.go

package mainimport "fmt"func main() {fmt.Println("Hello Go")
}
$ go run hello.go

运算符

算术运算符
运算符描述
+加法
-减法
*乘法
/除法
%取余
&位与
``
^位异或
&^位清除(非)
<<左移
>>右移
比较运算符
运算符描述
==等于
!=不等于
<小于
<=小于等于
>大于
>=大于等于
逻辑运算符
运算符描述
&&逻辑与
`
!逻辑非
其他
运算符描述
&取地址 / 创建指针
*解引用指针
<-发送 / 接收操作符(见下面的‘通道’部分)

声明

类型在标识符之后!

var foo int // declaration without initialization
var foo int = 42 // declaration with initialization
var foo, bar int = 42, 1302 // declare and init multiple vars at once
var foo = 42 // type omitted, will be inferred
foo := 42 // shorthand, only in func bodies, omit var keyword, type is always implicit
const constant = "This is a constant"// iota can be used for incrementing numbers, starting from 0
const (_ = iotaabc = 1 << iotad
)fmt.Println(a, b) // 1 2 (0 is skipped)fmt.Println(c, d) // 8 16 (2^3, 2^4)

函数

// a simple function
func functionName() {}// function with parameters (again, types go after identifiers)
func functionName(param1 string, param2 int) {}// multiple parameters of the same type
func functionName(param1, param2 int) {}// return type declaration
func functionName() int {return 42
}// Can return multiple values at once
func returnMulti() (int, string) {return 42, "foobar"
}
var x, str = returnMulti()// Return multiple named results simply by return
func returnMulti2() (n int, s string) {n = 42s = "foobar"// n and s will be returnedreturn
}
var x, str = returnMulti2()
函数作为值和闭包
func main() {// assign a function to a nameadd := func(a, b int) int {return a + b}// use the name to call the functionfmt.Println(add(3, 4))
}// Closures, lexically scoped: Functions can access values that were
// in scope when defining the function
func scope() func() int{outer_var := 2foo := func() int { return outer_var}return foo
}func another_scope() func() int{// won't compile because outer_var and foo not defined in this scopeouter_var = 444return foo
}// Closures
func outer() (func() int, int) {outer_var := 2inner := func() int {outer_var += 99 // outer_var from outer scope is mutated.return outer_var}inner()return inner, outer_var // return inner func and mutated outer_var 101
}
可变参数函数
func main() {fmt.Println(adder(1, 2, 3)) 	// 6fmt.Println(adder(9, 9))	// 18nums := []int{10, 20, 30}fmt.Println(adder(nums...))	// 60
}// By using ... before the type name of the last parameter you can indicate that it takes zero or more of those parameters.
// The function is invoked like any other function except we can pass as many arguments as we want.
func adder(args ...int) int {total := 0for _, v := range args { // Iterates over the arguments whatever the number.total += v}return total
}

内置类型

boolstringint  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptrbyte // alias for uint8rune // alias for int32 ~= a character (Unicode code point) - very Vikingfloat32 float64complex64 complex128

所有Go的预声明标识符都定义在builtin包中。

类型转换

var i int = 42
var f float64 = float64(i)
var u uint = uint(f)// alternative syntax
i := 42
f := float64(i)
u := uint(f)

  • 在每个源文件的顶部声明包
  • 可执行文件位于main包中
  • 约定:包的名称等于导入路径的最后一个部分(导入路径math/rand => 包rand
  • 大写标识符:导出的(可以从其他包中访问)
  • 小写标识符:私有的(不能从其他包中访问)

控制结构

判断
func main() {// Basic oneif x > 10 {return x} else if x == 10 {return 10} else {return -x}// You can put one statement before the conditionif a := b + c; a < 42 {return a} else {return a - 42}// Type assertion inside ifvar val interface{} = "foo"if str, ok := val.(string); ok {fmt.Println(str)}
}
循环
    // There's only `for`, no `while`, no `until`for i := 1; i < 10; i++ {}for ; i < 10;  { // while - loop}for i < 10  { // you can omit semicolons if there is only a condition}for { // you can omit the condition ~ while (true)}// use break/continue on current loop// use break/continue with label on outer loop
here:for i := 0; i < 2; i++ {for j := i + 1; j < 3; j++ {if i == 0 {continue here}fmt.Println(j)if j == 2 {break}}}there:for i := 0; i < 2; i++ {for j := i + 1; j < 3; j++ {if j == 1 {continue}fmt.Println(j)if j == 2 {break there}}}
条件
    // switch statementswitch operatingSystem {case "darwin":fmt.Println("Mac OS Hipster")// cases break automatically, no fallthrough by defaultcase "linux":fmt.Println("Linux Geek")default:// Windows, BSD, ...fmt.Println("Other")}// as with for and if, you can have an assignment statement before the switch valueswitch os := runtime.GOOS; os {case "darwin": ...}// you can also make comparisons in switch casesnumber := 42switch {case number < 42:fmt.Println("Smaller")case number == 42:fmt.Println("Equal")case number > 42:fmt.Println("Greater")}// cases can be presented in comma-separated listsvar char byte = '?'switch char {case ' ', '?', '&', '=', '#', '+', '%':fmt.Println("Should escape")}

数组, 切片, 遍历

数组
var a [10]int // declare an int array with length 10. Array length is part of the type!
a[3] = 42     // set elements
i := a[3]     // read elements// declare and initialize
var a = [2]int{1, 2}
a := [2]int{1, 2} //shorthand
a := [...]int{1, 2} // elipsis -> Compiler figures out array length
切片
var a []int                              // declare a slice - similar to an array, but length is unspecified
var a = []int {1, 2, 3, 4}               // declare and initialize a slice (backed by the array given implicitly)
a := []int{1, 2, 3, 4}                   // shorthand
chars := []string{0:"a", 2:"c", 1: "b"}  // ["a", "b", "c"]var b = a[lo:hi]	// creates a slice (view of the array) from index lo to hi-1
var b = a[1:4]		// slice from index 1 to 3
var b = a[:3]		// missing low index implies 0
var b = a[3:]		// missing high index implies len(a)
a =  append(a,17,3)	// append items to slice a
c := append(a,b...)	// concatenate slices a and b// create a slice with make
a = make([]byte, 5, 5)	// first arg length, second capacity
a = make([]byte, 5)	// capacity is optional// create a slice from an array
x := [3]string{"Лайка", "Белка", "Стрелка"}
s := x[:] // a slice referencing the storage of x
数组和切片的操作

len(a) 返回数组/切片的长度。这是一个内置函数,而不是数组的属性/方法。

// loop over an array/a slice
for i, e := range a {// i is the index, e the element
}// if you only need e:
for _, e := range a {// e is the element
}// ...and if you only need the index
for i := range a {
}// In Go pre-1.4, you'll get a compiler error if you're not using i and e.
// Go 1.4 introduced a variable-free form, so that you can do this
for range time.Tick(time.Second) {// do it once a sec
}

哈希表

m := make(map[string]int)
m["key"] = 42
fmt.Println(m["key"])delete(m, "key")elem, ok := m["key"] // test if key "key" is present and retrieve it, if so// map literal
var m = map[string]Vertex{"Bell Labs": {40.68433, -74.39967},"Google":    {37.42202, -122.08408},
}// iterate over map content
for key, value := range m {
}

结构体

Go中没有类,只有结构体。结构体可以拥有方法。

// A struct is a type. It's also a collection of fields// Declaration
type Vertex struct {X, Y float64
}// Creating
var v = Vertex{1, 2}
var v = Vertex{X: 1, Y: 2} // Creates a struct by defining values with keys
var v = []Vertex{{1,2},{5,2},{5,5}} // Initialize a slice of structs// Accessing members
v.X = 4// You can declare methods on structs. The struct you want to declare the
// method on (the receiving type) comes between the the func keyword and
// the method name. The struct is copied on each method call(!)
func (v Vertex) Abs() float64 {return math.Sqrt(v.X*v.X + v.Y*v.Y)
}// Call method
v.Abs()// For mutating methods, you need to use a pointer (see below) to the Struct
// as the type. With this, the struct value is not copied for the method call.
func (v *Vertex) add(n float64) {v.X += nv.Y += n
}

匿名结构体: 比使用 map[string]interface{} 更经济和更安全。

point := struct {X, Y int
}{1, 2}

指针

p := Vertex{1, 2}  // p is a Vertex
q := &p            // q is a pointer to a Vertex
r := &Vertex{1, 2} // r is also a pointer to a Vertex// The type of a pointer to a Vertex is *Vertexvar s *Vertex = new(Vertex) // new creates a pointer to a new struct instance

接口

// interface declaration
type Awesomizer interface {Awesomize() string
}// types do *not* declare to implement interfaces
type Foo struct {}// instead, types implicitly satisfy an interface if they implement all required methods
func (foo Foo) Awesomize() string {return "Awesome!"
}

嵌入

Go中没有子类化。相反,有接口和结构体嵌入。

// ReadWriter implementations must satisfy both Reader and Writer
type ReadWriter interface {ReaderWriter
}// Server exposes all the methods that Logger has
type Server struct {Host stringPort int*log.Logger
}// initialize the embedded type the usual way
server := &Server{"localhost", 80, log.New(...)}// methods implemented on the embedded struct are passed through
server.Log(...) // calls server.Logger.Log(...)// the field name of the embedded type is its type name (in this case Logger)
var logger *log.Logger = server.Logger

错误

Go中没有异常处理。相反,可能产生错误的函数只是声明了一个额外的返回值,类型为error。这是error接口:

// The error built-in interface type is the conventional interface for representing an error condition,
// with the nil value representing no error.
type error interface {Error() string
}

这是一个示例:

func sqrt(x float64) (float64, error) {if x < 0 {return 0, errors.New("negative value")}return math.Sqrt(x), nil
}func main() {val, err := sqrt(-1)if err != nil {// handle errorfmt.Println(err) // negative valuereturn}// All is good, use `val`.fmt.Println(val)
}

并发

协程

Goroutines是轻量级线程(由Go管理,而不是操作系统线程)。go f(a, b)启动一个新的goroutine来运行f(假设f是一个函数)。

// just a function (which can be later started as a goroutine)
func doStuff(s string) {
}func main() {// using a named function in a goroutinego doStuff("foobar")// using an anonymous inner function in a goroutinego func (x int) {// function body goes here}(42)
}

通道

ch := make(chan int) // create a channel of type int
ch <- 42             // Send a value to the channel ch.
v := <-ch            // Receive a value from ch// Non-buffered channels block. Read blocks when no value is available, write blocks until there is a read.// Create a buffered channel. Writing to a buffered channels does not block if less than <buffer size> unread values have been written.
ch := make(chan int, 100)close(ch) // closes the channel (only sender should close)// read from channel and test if it has been closed
v, ok := <-ch// if ok is false, channel has been closed// Read from channel until it is closed
for i := range ch {fmt.Println(i)
}// select blocks on multiple channel operations, if one unblocks, the corresponding case is executed
func doStuff(channelOut, channelIn chan int) {select {case channelOut <- 42:fmt.Println("We could write to channelOut!")case x := <- channelIn:fmt.Println("We could read from channelIn")case <-time.After(time.Second * 1):fmt.Println("timeout")}
}
通道原理
  • 向空通道发送会永远阻塞

    var c chan string
    c <- "Hello, World!"
    // fatal error: all goroutines are asleep - deadlock!
    
  • 从空通道接收会永远阻塞。

    var c chan string
    fmt.Println(<-c)
    // fatal error: all goroutines are asleep - deadlock!
    
  • 向已关闭的通道发送会引发恐慌。

    var c = make(chan string, 1)
    c <- "Hello, World!"
    close(c)
    c <- "Hello, Panic!"
    // panic: send on closed channel
    
  • 从已关闭的通道接收会立即返回零值。

    var c = make(chan int, 2)
    c <- 1
    c <- 2
    close(c)
    for i := 0; i < 3; i++ {fmt.Printf("%d ", <-c)
    }
    // 1 2 0
    

打印

fmt.Println("Hello, 你好, नमस्ते, Привет, ᎣᏏᏲ") // basic print, plus newline
p := struct { X, Y int }{ 17, 2 }
fmt.Println( "My point:", p, "x coord=", p.X ) // print structs, ints, etc
s := fmt.Sprintln( "My point:", p, "x coord=", p.X ) // print to string variablefmt.Printf("%d hex:%x bin:%b fp:%f sci:%e",17,17,17,17.0,17.0) // c-ish format
s2 := fmt.Sprintf( "%d %f", 17, 17.0 ) // formatted print to string variablehellomsg := `"Hello" in Chinese is 你好 ('Ni Hao')"Hello" in Hindi is नमस्ते ('Namaste')
` // multi-line string literal, using back-tick at beginning and end

反射

类型切换

类型切换类似于常规的switch语句,但类型切换中的情况指定要与给定接口值持有的值的类型进行比较的类型,而不是值。

func do(i interface{}) {switch v := i.(type) {case int:fmt.Printf("Twice %v is %v\n", v, v*2)case string:fmt.Printf("%q is %v bytes long\n", v, len(v))default:fmt.Printf("I don't know about type %T!\n", v)}
}func main() {do(21)do("hello")do(true)
}

片段

文件嵌入

Go程序可以使用"embed"包嵌入静态文件,如下所示:

package mainimport ("embed""log""net/http"
)// content holds the static content (2 files) for the web server.
//go:embed a.txt b.txt
var content embed.FSfunc main() {http.Handle("/", http.FileServer(http.FS(content)))log.Fatal(http.ListenAndServe(":8080", nil))
}

完整的Playground示例

HTTP服务器

package mainimport ("fmt""net/http"
)// define a type for the response
type Hello struct{}// let that type implement the ServeHTTP method (defined in interface http.Handler)
func (h Hello) ServeHTTP(w http.ResponseWriter, r *http.Request) {fmt.Fprint(w, "Hello!")
}func main() {var h Hellohttp.ListenAndServe("localhost:4000", h)
}// Here's the method signature of http.ServeHTTP:
// type Handler interface {
//     ServeHTTP(w http.ResponseWriter, r *http.Request)
// }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/147361.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

解决仪器掉线备忘

网络管控越来越严格&#xff0c;老的Mac模式连接的仪器经常断开&#xff0c;要么是网络没活动被断开TCP了&#xff0c;要么是网络波动无法保持TCP。每次重启仪器控制很麻烦&#xff0c;基于之前用M写http服务的基础上改进仪器接口连接。 参照之前实现http服务的逻辑 最终逻辑 …

如何解决版本不兼容Jar包冲突问题

如何解决版本不兼容Jar包冲突问题 引言 “老婆”和“妈妈”同时掉进水里&#xff0c;先救谁&#xff1f; 常言道&#xff1a;编码五分钟&#xff0c;解冲突两小时。作为Java开发来说&#xff0c;第一眼见到ClassNotFoundException、 NoSuchMethodException这些异常来说&…

VRRP配置案例(路由走向分析,端口切换)

以下配置图为例 PC1的配置 acsw下行为access口&#xff0c;上行为trunk口&#xff0c; 将g0/0/3划分到vlan100中 <Huawei>sys Enter system view, return user view with CtrlZ. [Huawei]sysname acsw [acsw] Sep 11 2023 18:15:48-08:00 acsw DS/4/DATASYNC_CFGCHANGE:O…

再次总结nios II 下载程序到板子上时出现 Downloading RLF Process failed的问题

之前也写过两篇关于NIOS II 出现&#xff1a;Downloading RLF Process failed的问题&#xff0c;但是总结都不是很全面&#xff0c;小梅哥的教程总结的比较全面特此记录。 问题&#xff1a;nios II 下载程序到板子上时出现 Downloading RLF Process failed的问题。 即当nios中…

《Jetpack Compose从入门到实战》 第二章 了解常用UI组件

目录 常用的基础组件文字组件图片组件按钮组件选择器组件对话框组件进度条组件 常用的布局组件布局Scaffold脚手架 列表 书附代码 Google的图标库 常用的基础组件 文字组件 Composable fun TestText() {Column(modifier Modifier.verticalScroll(state rememberScrollState…

Ubuntu20.04.1编译qt6.5.3版mysql驱动

下载qtbase6.5.3源码&#xff0c;将plugin中sqldrivers源码拷至于项目工程中&#xff0c;使用qtcreator打开文件 1、下载mysql开发库 sudo apt-get update sudo apt-get install build-essential libmysqlclient-dev 2、在msyql子目录中CMakeLists.txt第一行添加头文件、引…

浏览器指定DNS

edge--设置 https://dns.alidns.com/dns-query

前端页面初步开发

<template><div><el-card class"box-card" style"height: 620px"><el-input v-model"query.name" style"width:200px" placeholder"请输入用户姓名"></el-input>&nbsp&nbsp&nbsp…

yolov8 opencv模型部署(C++版)

yolov8 opencv模型部署&#xff08;C 版&#xff09; 使用opencv推理yolov8模型&#xff0c;仅依赖opencv&#xff0c;无需其他库&#xff0c;以yolov8s为例子&#xff0c;注意&#xff1a; 使用opencv4.8.0 &#xff01;使用opencv4.8.0 &#xff01;使用opencv4.8.0 &#…

有时候,使用 clang -g test.c 编译出可执行文件后,发现 gdb a.out 进行调试无法读取符号信息,为什么?

经过测试&#xff0c;gdb 并不是和所有版本的 llvm/clang 都兼容的 当 gdb 版本为 9.2 时&#xff0c;能支持 9.0.1-12 版本的 clang&#xff0c;但无法支持 16.0.6 版本的 clang 可以尝试使用 LLVM 专用的调试器 lldb 我尝试使用了 16.0.6 版本的 lldb 调试 16.0.6 的 clan…

string类的使用方式的介绍

目录 前言 1.什么是STL 2. STL的版本 3. STL的六大组件 4.STL的缺陷 5.string 5.1 为什么学习string类&#xff1f; 5.1.1 C语言中的字符串 5.2 标准库中的string类 5.3 string类的常用接口的使用 5.3.1 构造函数 5.3.2 string类对象的容量操作 5.3.3 string类对象…

Multiple CORS header ‘Access-Control-Allow-Origin‘ not allowed

今天在修改天天生鲜超市项目的时候&#xff0c;因为使用了前后端分离模式&#xff0c;前端通过网关统一转发请求到后端服务&#xff0c;但是第一次使用就遇到了问题&#xff0c;比如跨域问题&#xff1a; 但是&#xff0c;其实网关里是有配置跨域的&#xff0c;只是忘了把前端项…

画CMB天图使用Planck配色方案

使用Planck的配色方案&#xff1a; 全天图&#xff1a; 或者方形图&#xff1a; 使用下面设置即可&#xff1a; import pspy, pixell from pspy.so_config import DEFAULT_DATA_DIR pixell.colorize.mpl_setdefault("planck")此方法不会改变matplotlib默认配色方案…

虚拟机安装 centos

title: 虚拟机安装 centos createTime: 2020-12-13 12:00:27 updateTime: 2020-12-13 12:00:27 categories: linux tags: 虚拟机安装 centos 路线图 主机(宿主机) —> centos --> docker --> docker 镜像 --> docker 容器 — docker 服务 1.前期准备 一台 主机 或…

分类预测 | Matlab实现SSA-CNN-SVM麻雀算法优化卷积支持向量机分类预测

分类预测 | Matlab实现SSA-CNN-SVM麻雀算法优化卷积支持向量机分类预测 目录 分类预测 | Matlab实现SSA-CNN-SVM麻雀算法优化卷积支持向量机分类预测分类效果基本描述程序设计参考资料 分类效果 基本描述 1.Matlab实现SSA-CNN-SVM麻雀算法优化卷积支持向量机分类预测&#xff0…

TensorFlow入门(一、环境搭建)

一、下载安装Anaconda 下载地址:http://www.anaconda.comhttp://www.anaconda.com 下载完成后运行exe进行安装 二、下载cuda 下载地址:http://developer.nvidia.com/cuda-downloadshttp://developer.nvidia.com/cuda-downloads 下载完成后运行exe进行安装 安装后winR cmd进…

JAVA面经整理(5)

创建线程池不是说现用先创建&#xff0c;而是要是可以复用线程池中的线程&#xff0c;就很好地避免了大量用户态和内核态的交互&#xff0c;不需要频繁的创建和销毁线程 一)什么是池化技术&#xff1f;什么是线程池&#xff1f; 1)池化技术是提前准备好一些资源&#xff0c;在…

[React] 性能优化相关 (一)

文章目录 1.React.memo2.useMemo3.useCallback4.useTransition5.useDeferredValue 1.React.memo 当父组件被重新渲染的时候&#xff0c;也会触发子组件的重新渲染&#xff0c;这样就多出了无意义的性能开销。如果子组件的状态没有发生变化&#xff0c;则子组件是不需要被重新渲…

华为智能企业上网行为管理安全解决方案(1)

华为智能企业上网行为管理安全解决方案&#xff08;1&#xff09; 课程地址方案背景需求分析企业上网行为概述企业上网行为安全风险分析企业上网行为管理需求分析 方案设计组网架构设备选型设备简介行为管理要点分析方案功能概述 课程地址 本方案相关课程资源已在华为O3社区发…

网络协议--概述

1.2 分层 网络协议通常分不同层次进行开发&#xff0c;每一层分别负责不同的通信功能。一个协议族&#xff0c;比如TCP/IP&#xff0c;是一组不同层次上的多个协议的组合。TCP/IP通常被认为是一个四层协议系统&#xff0c;如图1-1所示。 每一层负责不同的功能&#xff1a; 1.…