Golang 学习资料

资料

1.How to Write Go Code

https://golang.org/doc/code.html

2.A Tour of Go

https://tour.golang.org/list

3.Effective Go

https://golang.org/doc/effective_go.html

4.Visit the documentation page for a set of in-depth articles about the Go language and its libraries and tools.

https://golang.org/doc/#articles

Packages,variables,and functions

Packages

  • Every Go program is made up of packages
  • Programs start running in package main
  • In Go,a name is exported if it begins with a capital.

Functions

  • type comes after the variable name.
  • When two or more consecutive named function parameters share a type,you can omit the type from all but the last.
  • A function can return any number of results

Variables

  • The var statement declares a list of variables
  • Inside a function,the := short assigment statement can be used in place of a var declaration with implicit type.
  • Variables declared without an explicit initial value are given their zero value.
  • The expression T(v) converts the value v to the type T.Go assignment between items of different type requires an explicit conversion.
  • Constants are declared like variables,but with the const keyword(Constants cannot be declared using the := syntax)

Flow control statements: for,if,else,switch and defer

for

  • unlike other languages like C,java there are no parentheses surrounding the three components of the for statement and the braces {} are always required.
  • The init statement will often be a short variable declaration,and the varaibles there are visible only in the scope of the for statement
  • The init and post statements are optional.
  • You can drop the semicolons:C's while is spelled for in Go.
  • If you omit the loop condition it loops forever,so an infinite loop is compactly expressed.

If

  • Go's if statements are like its for loops;the expression need not be surrounded by parentheses() but the braces {} are required.
  • Like for,the if statement can start with a short statement to execute before the condition
  • Variables declared inside an if short statement are also available inside any of the else blocks.

sort:

package mainimport ("fmt"
)func main(){arr := []int{1,5,3,2,6,3,4,8,7,0}for i:=0;i<len(arr);i++{fmt.Printf("%d ",arr[i]);}fmt.Printf("\nSorting\n");for i:=0;i<len(arr);i++{for j:= i+1;j<len(arr);j++{if arr[i]>arr[j]{arr[i],arr[j] = arr[j],arr[i]}}}for i:=0;i<len(arr);i++{fmt.Printf("%d ",arr[i]);}fmt.Printf("\n");
}

Switch

  • In effect,the break statement that is needed at the end of each case in those languages(C,C++) is provided automatically in Go.
  • Go's switch cases need not be constants,and the values involved need not be integers
  • Switch cases evaluate cases from top to bottom,stopping when a case succeeds.
  • Switch without a condition is the sames as switch true.

Defer

  • A defer statement defers the execution of a function until the surrounding function returns.The deferred call's arguments are evaluated immediately.
  • Deferred function calls are pushed onto stack.When a function returns,its deferred calls are executed in last-in-first-out-order.

More types:structs,slices,and maps.

Pointers

  • The type *T is a pointer to a T value.Its zero value is nil.
  • Unlike C,Go has no pointer arithmetic

Structs

  • A struct is a collection of fields.
  • Struct fields are accessed using a dot.

Pointers to struct

  • To access the field X of a struct when we have the struct pointer p we could write (*p).X.However,that notation is cumbersome,so the language permits us instead to write just p.X,without the explicit dereference.

Struct Literals

  • A struct literal denotes a newly allocated struct value by listing the values of its fields.You can list just a subset of fields by using the Name: syntax.

Arrays

  • The type [n]T is an array of n values of type T.

Slices

  • An array has a fixed size.A slice ,on the other hand , is a dynamically-sized,flexible view into the elements of an array.
  • The type []T is a slice with elements of type T.
  • A slice if formed by specifying two indices,a low and high bound,separated by a colon:a[low:high],This selects a half-open range which includes the first element,but excludes the last one.

Slices are like reference to arrays

  • A slice does not store any data,it just describes a section of an underlying array.
  • Changing the elements of a slice modifies the corresponding elements of its underlying array.
  • Other slices that share the same underlying array will see those changes.

Slice literals

  • A slice literal is like an array literal without the length

Slice defaults

  • When slicing,you may omit the high or low bounds to use their defaults instead.The default is zero for the low bound and the length of the slice for the high bound.

Slice length and capacity

  • A slice has both a length and a capacity.
  • The length of a slice is the number of elements it contains
  • The capacity of a slice is the number of elements in the underlying array,counting from the first element in the slice.
  • The length and capacity of a slice s can be obtained using the expression len(s) and cap(s)

Nil Slices

  • The zero value of a slice is nil.

Creating a slice with make

  • Slices can be created with the built-in make function;this is how you create dynamically-sized arrays.
  • The make function allocates a zeroed array and returns a slice that refers to that array:
a:=make([]int,5)//len(a)=5
  • To specify a capacity,pass a third argument to make:

Appending to a slice

  • it is common to append new elements to a slice,and so Go provides a built-in append function.
func append(s []T,vs ....T)[]T
  • The resulting value of append is a slice containing all the elements of the original slice plus the provided values.
  • If the backing array of s is too small to fit all the given values a bigger array will be allocated.The returned slice will point to the newly allocated array.

Range

  • The range form of the loop iterates over a slice or map.
  • When ranging over a slice,two values are returned for each iteration.The first is the index,and the second is a copy of the element at that index.
  • You can skip the index or value by assigning to _.
  • If you only want the index,drop the , value entirely.

Maps

  • A map maps keys to values.
  • The make function returns a map of the given type,initialized and ready for use.
  • Delete an element:
delete(m,key)
  • Test that a key is present with a two-value assignment:
elem,ok = m[key]

if key is not in the map,then elem is the zero value for the map's element type.

Function values

  • Functions are values too.They can be passed around just like other values.
  • Function values may be used as function arguments and return values

Function closures

  • Go functions may be closures.A closure is a function value that referenes variables from outside its body.The function may access and assign to the referenced variables;in this sense the function is "bound" to the variables

Methods and interfaces

Method

  • Go does not have classes.However,you can define methods on types.
  • A method is a function with a special receiver argument.
  • The receive appears in its own argument list between the func keyword and the method name.
  • Remember:a method is just a function with a receiver argument.
  • You cannot declare a method with a receiver whose type is defined in another package(which includes the built-in types such as int)
  • You can declare methods with pointer receivers.This means the receiver type has the literal syntax T for some type T.(Also,T cannot itself be a pointer such as int.)

Methods and pointer indirection

  • methods with pointer receivers take either a value or a pointer as the receiver when they are called.(The equivalent thing happends in the reverse direction)

Choosing a value or pointer receiver

  • There are two reasons to use a pointer receiver.
  • The first is so that the method can modify the value that its receiver points to.
  • The second is to avoid copying the value on each method call.This can be more efficient if the receiver is a large struct.
  • In general,all methods on a given type should have either value or pointer receivers,but not a mixture of both.

Interfaces

  • An interface type is defined as a set of method signatures.
  • A value of interface type can hold any value that implements those methods.

Interfaces are implemented implicitly

  • A type implements an interface by implementing its methods.There is no explicit declaration of intent,no "implements" keyword.

Interface values

  • Under the hood,interface values can be thought of as a tuple of a value and a concrete type:
  • An interface value holds a value of a specific underlying concrete type.
  • Calling a method on an interface value executes the method of the same name on its underlying type.

Interface values with nil underlying values

  • If the concrete value inside the interface itself is nil,the method will be called with a nil receiver.
  • Note that an interface value that holds a nil concrete value is itself non-nil

Nil interface value

  • A nil interface value holds neither value nor concrete type.

The empty interface

  • The interface type that specifies zero methods is known as the empty interface.
  • An empty interface may hold values of any type.
  • Empty interfaces are used by code that handles vallues of unknown type.

Type assertions

  • A type assertion provides access to an interface value's underlying concrete value.
t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

Type switches

  • A type switch is a construct that permits serveral type assertions in series.
switch v := i.(type){case T://here v has type Tdefault://no match
}

A type switch is like a regular switch statement,but the cases in a type switch specify type(not value),and those values are compared against the type of the value held by the given interface value.

The declaration in a type switch has the same syntax as a type assertion i.(T),but the specific type T is replaced with the keyword type.

Stringers

one of the most ubiquitous interfaces is Stringer defined by the fmt package.

type Stringer interface{String() string
}

A Stringer is a type that can describe itself as string.The fmt package look for this interface to print values.

Errors

Go programs express error state with error values.

  • A nil error denotes success;a non-nil error denotes failure.

Reader

  • The io package specifies the io.Reader interface,which represents the read end of a stream of data.
  • The Go standard library contains many implementations of these interfaces,including files,network connections,compressors,ciphers,and others.
  • The io.Reader interface has a Read method:
func (T)Read(b []byte)(n int,err error)

Read populates the given byte slice with data and returns the number if bytes populated and an error value.It returns an io.EOF error when the stream ends

Image

Package image defines the Image interface

package image
type Image interface{ColorModel() color.ModelBounds() RectangleAt(x,y int) color.Color
}

Concurrency

Goroutines

A goroutine is a lightweight thread managed by by the Go runtime.

go f(x,y,z)

starts a new goroutine running

f(x,y,z)

Goroutines run the same address space,so access to shared memory must be synchronized.The sync package provides useful primitives,althought you wan't need them much in Go as there are other primtives.

Channels

  • Channels are a typed conduit through which you can send and receive values with the channel operator,<-
  • Like maps and slices,channels must be created before use:
ch:=make(chan int)
  • By default,sends and receives block until the other side is ready.This allows goroutines to synchronize without explicit locks or condition variables.

Buffered Channels

  • Channels can be buffered.Provide the buffer length as the second argument to make to initialize a buffered channel:
ch := make(chan int,100)
  • Sends to a buffered channel block only when the buffer is full.Receives block when the buffer is empty.

Range and Close

  • A sender can close a channel to indicate that no more values will be sent.Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression:
v,ok:=<-ch
  • The loop for i:= range c receives values from the channel repeatedly until it is closed.

Select

  • The select statement lets a goroutine wait on multiple communication operations.
  • A select blocks until one of its cases can run,then it executes that case.It chooses one at random if multiple are ready.

Default Selection

  • The default case in a select is run if no other case is ready.
  • Use a default case to try a send or receive without blocking
select {
case i := <-c://use i
default://receiving frim c would block
}

sync.Mutex

What if we just want to make sure only one goroutine can access a variable at a time to avoid conflicts

The concept is called mutual exclusion,and the conventional name for the data structure that provides it is mutex

Go's standard libaray provides mutual exclusion with sync.Mutext and its two methods:

Lock
Unlock

转载于:https://www.cnblogs.com/r1ng0/p/10196858.html

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【软考】[信息安全工程师]

【背景】 有一定的基础&#xff0c;于2019年5月的考试上岸&#xff0c;复习了两周左右。奥里给&#xff01; 【备考资料】 【参考网站】 信管网 http://www.cnitpm.com/aq/ 月梦工作室 https://www.moondream.cn/ 含历年试题以及参考答案 【参考教材】 信息安全工程师五天…

java学习(134):泛型通配符的使用

import java.util.ArrayList; import java.util.List;//泛型通配符的使用 public class test73 {public static void main(String[] args){List<Integer> intListnew ArrayList<Integer>();intList.add(new Integer(100));intList.add(new Integer(200));List<?…

java dictionary遍历_遍历 Dictionary,你会几种方式?

一&#xff1a;背景1. 讲故事昨天在 StackOverflow 上看到一个很有趣的问题&#xff0c;说: 你会几种遍历字典的方式&#xff0c;然后跟帖就是各种奇葩的回答&#xff0c;挺有意思&#xff0c;马上就要国庆了&#xff0c;娱乐娱乐吧&#xff0c;说说这种挺无聊的问题&#x1f6…

【SP26073】DIVCNT1 - Counting Divisors 题解

题目描述 定义 \(d(n)\) 为 \(n\) 的正因数的个数&#xff0c;比如 \(d(2) 2, d(6) 4\)。 令 $ S_1(n) \sum_{i1}^n d(i) $ 给定 \(n\)&#xff0c;求 \(S_1(n)\)。 输入格式 第一行包含一个正整数 \(T\) (\(T \leq 10^5\))&#xff0c;表示数据组数。 接下来的 \(T\) 行&am…

密码系统的安全性

1&#xff0c;评估密码系统安全性主要有三种方法&#xff1a; &#xff08;1&#xff09;无条件安全性 这种评价方法考虑的是假定攻击者拥有无限的计算资源&#xff0c;但仍然无法破译该密码系统。 &#xff08;2&#xff09;计算安全性 这种方法是指使用目前最好的方法攻破…

java学习(135):map中泛型使用

定义一个员工类 public class Employee {private String name;private String ags;public void setName(String name) {this.name name;}public String getName() {return name;}public void setAgs(String ags) {this.ags ags;}public String getAgs() {return ags;} }定义…

java两种绑定方式_Javascript绑定事件的两种方式的区别

命名函数function check(){//code}匿名函数window.onload function(){//先获取元素对象&#xff0c;再绑定事件&#xff0c;绑定的是匿名函数不可重用var btn document.getElementById("btn");btn.onclick function(){//code}}以前一直以为两种方式的区别不大&…

前端基础_认识前端.md

前端学习 前端学习路线学习网站 菜鸟驿站慕课网freeCOdeCampw3schooltry8在线编辑 codepenjsfiddlethecodeplayer其他网站 cssfilterscssstats极客学院搭建个人博客wordpress博客园网站检查规范How to learn webTobe continue... 学习准备 查看浏览器占有的市场份额 查看浏览器…

[剑指offer][JAVA][第62题][约瑟夫环][LinkedList vs ArrayList]

【问题描述】 面试题62. 圆圈中最后剩下的数字 0,1,,n-1这n个数字排成一个圆圈&#xff0c;从数字0开始&#xff0c;每次从这个圆圈里删除第m个数字。求出这个圆圈里剩下的最后一个数字。例如&#xff0c;0、1、2、3、4这5个数字组成一个圆圈&#xff0c;从数字0开始每次删除第…

java创建两个foo方法_Java类实例化原理 - osc_foo7glsg的个人空间 - OSCHINA - 中文开源技术交流社区...

Java对象的创建过程包括类初始化(类实例化两个阶段。一、Java对象创建时机(1)使用new关键字创建对象(2)反射创建对象使用Class类的newInstance方法Student student2 (Student)Class.forName("Student类全限定名").newInstance()&#xff1b;使用Constructor类的newI…

java学习(136):带泛型的类

SuppressWarnings("all") public class GJClass<T> {public String getClassName(T t){return t.getClass().getName();} } 测试类 public class test76 {public static void main(String[] args){GJClass gjClassnew GJClass();String classNamegjClass.get…

如何往eclipse中导入maven项目

现在公司中大部分项目可能都是使用maven来构建&#xff0c;假如现在摆在你面前有一个maven的项目&#xff0c;如果你要学习它&#xff0c;如何将它导入到像eclipse这样的集成开发工具中呢&#xff0c;以项目public_class_1为例&#xff1a; 1.在eclipse的工作界面的最左侧&…

[Leetcode][JAVA][第912题][排序算法]

【问题描述】 给你一个整数数组 nums&#xff0c;将该数组升序排列。 示例 1&#xff1a; 输入&#xff1a;nums [5,2,3,1] 输出&#xff1a;[1,2,3,5]【解答思路】 1.插入排序&#xff08;熟悉&#xff09; 每次将一个数字插入一个有序的数组里&#xff0c;成为一个长度更…

java 调用r语言包传参数_Java与R语言的配置,调用

我是最近才接触到了R语言&#xff0c;所以用起来有很多的问题&#xff0c;之前只是想单纯想用java调用到R语言中的一些东西&#xff0c;没有想到这个事情并不是想象的那么简单的。好了&#xff0c;闲话不多说&#xff0c;下面我来说说我在运用R的时候遇上的问题吧。第一步&…

玩转oracle 11g(42):增加表空间

--查询表空间 select t.tablespace_name, d.file_name, d.autoextensible, d.maxbytes, d.status from dba_tablespaces t, dba_data_files d where t.tablespace_name d.tablespace_name order by tablespace_name.file_name; --增加表空间 AL…

php下载文件添加header响应头

header(Content-type:application/octet-stream);header(Content-Disposition:attachment;filename".basename($file).");header(Content-Length:.filesize($file));readfile($file);转载于:https://www.cnblogs.com/jielin/p/10203140.html

[Leetcode][JAVA][第1111题][栈思想]

【问题描述】 有效括号字符串 定义&#xff1a;对于每个左括号&#xff0c;都能找到与之对应的右括号&#xff0c;反之亦然。详情参见题末「有效括号字符串」部分。嵌套深度 depth 定义&#xff1a;即有效括号字符串嵌套的层数&#xff0c;depth(A) 表示有效括号字符串 A 的嵌…

玩转oracle 11g(43):oracle导出空表

因为11G数据库在CREATE表后数据库不会立刻给该表分配物理存储空间&#xff0c;所以导出数据库的时候自然而然不会导出该表。 解决方案&#xff1a;在导出表服务器上找出所有数据为空的表&#xff0c;批处理的给没有数据行的数据表分配存储空间。 方法1.此为分步骤执行&#x…

分类器交叉验证java_使用交叉验证的KNN分类器

首先&#xff0c;您需要准确定义您的任务 . F.ex给出R ^(MxN)中的图像I&#xff0c;我们希望将I分类为包含面部的图像或没有面部的图像 .我经常使用像素分类器&#xff0c;其任务类似于&#xff1a;对于图像&#xff0c;我决定每个像素是面像素还是非面像素 .定义任务的一个重要…

Python——assert(断言函数)

一、断言函数的作用 python assert断言是声明其布尔值必须为真的判定&#xff0c;如果发生异常就说明表达示为假。可以理解assert断言语句为raise-if-not&#xff0c;用来测试表示式&#xff0c;其返回值为假&#xff0c;就会触发异常。 二、常用格式 assert 11  assert 222*…