当前位置:网站首页>Go language tutorial 01 go tools +go syntax +go module
Go language tutorial 01 go tools +go syntax +go module
2022-06-09 05:46:00 【liaomin416100569】
List of articles
go course
go brief introduction
Go Is an open source programming language , It makes construction simple 、 Reliable and efficient software becomes easy .
Go It's from 2007 Year end by Robert Griesemer, Rob Pike, Ken Thompson Host development , Later I joined in Ian Lance Taylor, Russ Cox wait forsomeone , And finally 2009 year 11 In open source , stay 2012 Released earlier this year Go 1 Stable version . Now? Go The development of is completely open , And have an active community .
Related websites :
go Official website :https://golang.org/pkg/
go Dependent package search :https://godoc.org/
go install
The download address of the installation package is :https://golang.org/dl/.
window The default installation directory is :c:/go,bin The directory automatically points to bin Catalog .
linux decompression tgz package , take bin Directory added to PATH variable , hypothesis go Unzip in /opt/go Under the table of contents
cat << 'EOF' >> ~/.bash_profile
PATH=$PATH:/opt/go/bin
export PATH
EOF
test go Whether it is installed normally
C:\Users\GVT>go version
go version go1.14.2 windows/amd64
go Common commands
Input directly in the terminal go help All can be displayed go Command and the corresponding command function , There are basically the following :
- build: Compile packages and dependencies
- clean: Remove object file
- doc: A document that displays packages or symbols
- env: Print go Environmental information
- bug: Startup error reporting
- fix: function go tool fix
- fmt: function gofmt format
- generate: from processing source Generate go file
- get: Download and install packages and dependencies
- install: Compile and install packages and dependencies
- list: List the package
- run: Compile and run go Program
- test: Run the test
- tool: function go Tools provided
- version: Show go Version of
- vet: function go tool vet
The command is used as : go command [args], besides , have access to go help To display more help information for the specified command .
Running go help when , More than just printing the basic information for these commands , Some helpful information about concepts is also given :
- c: Go and c Mutual call
- buildmode: Description of the build pattern
- filetype: file type
- gopath: GOPATH environment variable
- environment: environment variable
- importpath: Import path syntax
- packages: Description of the package list
- testflag: Test symbol description
- testfunc: Test function description
Also use go help To see information about these concepts .
build and run command
Just like any other statically typed language , To execute go Program , You need to compile , Then in the execution of the generated executable file .go build The command is used to compile go The program generates executable files . But that's not why go Programs can be compiled to generate executable files , To generate an executable file ,go The program has to satisfy two conditions :
- The go Program needs to belong to main package
- stay main The package must also contain main function
in other words go The entry point of the program is main.main, namely main Under bag main function , Example (hello.go):
cat <<EOF > hello.go
package main
import "fmt"
func main(){
fmt.Println("Hello World")
}
EOF
compile hello.go, Then run the executable :
go build hello.go
Generated in the current directory hello.exe, function
[email protected] MINGW64 ~/go
$ ./hello.exe
Hello World
and go run The command can execute the above two steps in one ( No intermediate file will be generated ).
$ go run hello.go
Hello World!
The above two commands are very common in development .
Besides go clean command , Can be used to clear the generated executable :
$ go clean # Without parameters , You can delete all the executable files in the current directory
$ go clean sourcefile.go # Will delete the corresponding executable file
fmt and doc command
go Languages have a mixed feature , It's very strict with the format , I love this feature , Because you can keep the code clean and consistent , Compile portfolio development , also go It also provides a very powerful tool for formatting code , It is go fmt sourcefile.go, But usually you don't really need to call it manually , Various editors can help us to do the formatting automatically .
go doc The command allows us to quickly view package documents ,go doc package The command will print out the specification in the terminal package Documents .
If you look at fmt file
go doc fmt
And then there's a delta go doc The relevant command is godoc, It allows us to start our own document server :
godoc -http=:8080
Then we can work with in the browser localhost:8080 View in go Document.
godoc No executable program by default , Generate executable program steps
git clone https://github.com/golang/tools golang.org/x/tools
go The installation directory /src newly build golang.org\x\tools Catalog Copy the source code to this directory
cd C:\Go\src\golang.org\x\tools\godoc
go build golang.org/x/tools/cmd/godoc
go install golang.org/x/tools/cmd/godoc Automatically copy to bin Catalog
install command
Used to compile and install go Program , We can relate it to build Command comparison :
Generated executable path In the working directory bin Under the table of contents Under current directory
The name of the executable It has the same name as the directory where the source code is located The default name is the same as the source program , have access to -o Option assignment
rely on Put the dependent packages in the working directory pkg Under the folder -
| build | build | |
|---|---|---|
| Generated executable path | In the working directory bin Under the table of contents | Under current directory |
| The name of the executable | It has the same name as the directory where the source code is located | The default name is the same as the source program , have access to -o Option assignment |
| rely on | Put the dependent packages in the working directory pkg Under the folder | - |
env command
View all environment variables
go env
go env | grep GOROOT
Modify environment variables ( Set up agents in China or alicloud :https://mirrors.aliyun.com/goproxy/)
go env -w GOPROXY=https://goproxy.cn
get command
go get The command can pull or update the code package and its dependent packages remotely with the help of the code management tool , And automatically complete the compilation and installation . The whole process is like installing one App It's as simple as .
This command can dynamically get the remote code package , Currently supported BitBucket、GitHub、Google Code and Launchpad. In the use of go get Before the command , You need to install a code management tool that matches the remote package , Such as Git、SVN、HG etc. , You need to provide a package name in the parameter .
This command is actually divided into two steps inside : The first step is to download the source code package , The second step is to execute go install. Download the source package go The tool will automatically call different source tools according to different domain names , The correspondence is as follows :
BitBucket (Mercurial Git)
GitHub (Git)
Google Code Project Hosting (Git, Mercurial, Subversion)
Launchpad (Bazaar)
So for go get The command works properly , You must ensure that the appropriate source management tools are installed , And add these commands to your PATH in . Actually go get Support the function of custom domain name .
Parameter Introduction :
- -d Download only and do not install
- -f Only if you include -u Parameter is valid , Not allow -u To verify import Each of them has acquired , This is for local fork Your bag is particularly useful
- -fix After obtaining the source code, run fix, And then do other things
- -t Also download the packages needed to run the tests
- -u Force the use of the network to update the package and its dependent packages
- -v Displays the commands executed
Go The language code is hosted in Github.com Website , The site is based on Git Code management tools , Many well-known projects host code on the site . Other similar hosting sites are available code.google.com、bitbucket.org etc. .
The project package paths for these sites all have a common standard , See the figure below
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-lZFb5vnB-1589278910682)(images/1.jpg)]
The remote package path in the figure is Go Language source code , This path is co-dependent 3 Component composition :
- Website domain name : Represents a code hosted web site , Similar to email @ The server address in the back .
- Author or institution : Indicate the ownership of the project , Generally, it is the user name of the website , If you need to find all the items under this author , It can be searched directly on the website “ domain name / author ” To view the . This section is similar to email @ Front part .
- Project name : The author or organization under each website may have many projects at the same time , The sections marked in the figure represent the project name .
By default ,go get You can use it directly . for example , Want to get go The source code and compile , Use the following command line :
go get github.com/davyxu/cellnet
Before acquisition , Please make sure GOPATH Have been set .Go 1.8 After the version ,GOPATH The default is in the user directory go Under the folder .
cellnet It's just a network library , There is no executable file , So in go get After successful operation GOPATH Under the bin There will not be any compiled binaries in the directory .
You need to test to get and compile the binary , Try the following command . When the fetch is complete , It will automatically be here GOPATH Of bin Generate the compiled binaries in the directory .
go get -u github.com/gpmgo/gopm
View your GOPATH/bin Whether to generate gopm.exe,src Is there a gpmgo Source code .
go package
The basic concept of the package
Go Language packages are organized in the form of a directory tree , Generally, the name of a package is the name of the directory where its source file is located , although Go The language does not require that the package name must have the same name as the directory name in which it is located , However, it is recommended that the package name should have the same name as the directory , This makes the structure clearer .
Packages can be defined in deep directories , The definition of package name does not include directory path , However, packages generally use full path references when referencing . For example GOPATH/src/a/b/ Define a package c. In the bag c You only need to declare as package c, Instead of declaring package a/b/c, But when importing c Packet time , You need to bring the path , for example import “a/b/c”.
Package idioms :
- The package name is usually lowercase , Use a short and meaningful name .
- Generally, the package name should have the same name as the directory , It can be different , Package name cannot contain - Equal special symbol .
- Packages generally use domain names as directory names , This ensures the uniqueness of the package name , such as GitHub The package of the project is usually placed in GOPATH/src/github.com/userName/projectName Under the table of contents .
- Package name is main The package of is the entry package of the application , Compilation does not include main Package source code files will not get executable files .
All source files in a folder can only belong to the same package , Similarly, source files belonging to the same package cannot be placed in multiple folders .
Package import
Single line import
import " package 1 The path of "
import " package 2 The path of "
Multiline import
import (
" package 1 The path of "
" package 2 The path of "
)
Alias
package main
import F "fmt"
func main() {
F.Println("C Chinese language network ")
}
Omit the reference
package main
import . "fmt"
func main() {
// No need to prefix fmt.
Println("C Chinese language network ")
}
The standard Go The language code base contains a large number of packages , And installing Go Most of them will be installed into the system automatically . We can do it in $GOROOT/src/pkg Check out these packages in the catalog . The following is a brief introduction to some commonly used packages in our development .
- fmt
fmt Package implements formatted standard input and output , This is related to C In language printf and scanf similar . Among them fmt.Printf() and fmt.Println() Is the most frequently used function by developers .
A formatted phrase derives from C Language , Some phrases (%- Sequence ) This is how to use :
- %v: Default format value . When printing structures , plus (%+v) Field name will be added ;
- %#v:Go The value representation of the style ;
- %T: With type Go The value representation of the style .
- io
This package provides the original I/O interface . Its main task is to os It's a primitive package I/O encapsulate , Add some other relevant , Make it abstract for public interfaces . - bufio
bufio Package through pair io Package packaging , Provides data buffering function , It can reduce the cost of large data reading and writing to a certain extent .
stay bufio A buffer is maintained inside each component , Data read and write operations are directly through the cache . When a read-write operation is initiated , Will first try to get data from the buffer , Only when the buffer has no data , To get the data update buffer from the data source . - sort
sort Packages provide the ability to sort slices and user-defined collections . - strconv
strconv Package provides conversion of strings to basic data types , Or the ability to convert from a basic data type to a string . - os
os The package provides a platform independent interface to the operating system functions , Design image Unix style , But error handling is go style , When os When the bag is in use , If the error type is returned instead of the number of errors . - sync
sync The package implements the lock mechanism in multithreading and other synchronization and mutual exclusion mechanisms . - flag
flag The package provides the rule definition of command line parameters and the function of parsing the input parameters . Most command-line programs need this package . - encoding/json
JSON At present, it is widely used as the communication format in network program .encoding/json The package provides JSON Basic support for , For example, serialize from an object to JSON character string , Or from JSON String deserialization to a specific object, etc . - html/template
Mainly achieved web Generate in development html Of template Some functions of . - net/http
net/http Package supply HTTP Related services , It mainly includes http request 、 Response and URL Parsing , And basic http Client and extended http service .
adopt net/http package , Just a few lines of code , You can implement a crawler or a Web The server , This is unimaginable in traditional languages . - reflect
reflect The package implements runtime reflection , Allows programs to manipulate objects through abstract types . Usually used to handle static types interface{} Value , And through Typeof Analyze its dynamic type information , Usually, an interface type is returned Type The object of . - os/exec
os/exec Packages provide execution customization linux The implementation of the command . - strings
strings Package is a collection of functions dealing with strings , Including merger 、 lookup 、 Division 、 Compare 、 Suffix check 、 Indexes 、 Case processing and so on .
strings Bag and bytes The function interface function of the package is basically the same . - bytes
bytes Package provides a series of functions to read and write byte slices . Byte slicing has more functions , It is divided into basic processing functions 、 Comparison function 、 Suffix checking function 、 Index function 、 Partition function 、 Case processing function and sub slice processing function, etc . - log
log Package is mainly used to output log in program .
log Three kinds of log output interfaces are provided in the package ,Print、Fatal and Panic.
- Print It's normal output ;
- Fatal It's the end of execution Print after , perform os.Exit(1);
- Panic It's the end of execution Print After the call panic() Method .
Package management tools
except go Tools included in the tool chain, such as ,go build 、go vet 、go get 、 go doc wait , There are also package dependency management tools . such as dep wait ,go 1.11 1.12 And added go modules .
Always rely on go What people roast about language is package dependency management and Error handling . A number of package dependency management tools have emerged in the community .
GOROOT and GOPATH difference
Two concepts :GOROOT and GOPATH
- GOROOT: System environment variable , It is what we store and download go Language source code (go Source code , It wasn't written by us ).
- GOPATH: environment variable , Our workspace , Include bin、pkg、src. It is used to store the code we wrote and the downloaded third-party code .
rely on , There are internal dependencies and external dependencies .
- Internal dependence :
GOPATH and GOROOT,GOROOT It doesn't have to be set , however GOPATH You have to set , But it is not fixed . The internal dependencies of the project will be in GOPATH Go to the configured path to find , The compiler will report an error if it cannot find it . In general, internal dependencies don't need to worry too much .
- External dependency packages :
When we want to implement some functions , The inevitable need for some third-party packages , Also referred to as external dependency packages .go1.5 Previously, only GOPATH To manage external dependent packages , contrast java Of maven and gradle etc. It's not very convenient .
Vendor Mechanism Introduction
stay go1.5release Before , When we want to manage multiple dependent package versions , You can only set multiple GOPATH, Copy the code to solve . such as , If both projects rely on Beego, One 1.5, One 1.8, Then two must be set GOPATH, And remember to switch .
go Language native package defects :
The platforms that can pull the source code are very limited , Most rely on github.com
Can't distinguish version , So that developers can use the last package name as the version partition
rely on list / Relationship Can't persist to local , You need to find all the dependency packages and one by one go get
It can only rely on the local global warehouse (GOPATH/GOROOT), Can't put the library in a local warehouse ($PROJECT_HOME/vendor)
In short , That is, there is one more in your project vendor Folder ,go It will default to GOPATH. Give Way go Compile time , Take priority from the project source code tree root directory vendor Directory lookup code ( It can be understood as cutting once GOPATH), If vendor There is , No more GOPATH To find the .
Community support vendor There are many package management libraries in , The official recommendations are 15 Kind of .
There are a lot of dep( official )、Godep、Govendor wait
go The official package management tool is dep, At present, it is also the most used , It is officially recommended .
official wiki Various comparisons : https://github.com/golang/go/wiki/PackageManagementTools
The installation method is also relatively simple , Download the corresponding platform executable :https://github.com/golang/dep/releases, copy to GOROOT/bin Catalog
In your own working directory , Use dep Initialization will report an error :
$ dep init
init failed: unable to detect the containing GOPATH: /home/zhongwei/work/my_project/go is not within a known GOPATH/src
In other words, project development is defined in GOPATH Directory can be used
Don't want to put the new project directory my_project/go Add to GOPATH in , Feel very troublesome , Besides, I did consul Source code discovery has been switched to go module, At this point, I have to give up dep.
Go Modules
Use go module After managing dependencies, two files will be generated in the root directory of the project go.mod and go.sum.
go.mod The dependency of the current project will be recorded in , The file format is as follows :
module github.com/gosoon/audit-webhook
go 1.12
require (
github.com/elastic/go-elasticsearch v0.0.0
github.com/gorilla/mux v1.7.2
github.com/gosoon/glog v0.0.0-20180521124921-a5fbfb162a81
)
go.sum Record the version and hash value of each dependency library , The file format is as follows :
github.com/elastic/go-elasticsearch v0.0.0 h1:Pd5fqOuBxKxv83b0+xOAJDAkziWYwFinWnBO0y+TZaA=
github.com/elastic/go-elasticsearch v0.0.0/go.mod h1:TkBSJBuTyFdBnrNqoPc54FN0vKf5c04IdM4zuStJ7xg=
github.com/gorilla/mux v1.7.2 h1:zoNxOV7WjqXptQOVngLmcSQgXmgk4NMz1HibBchjl/I=
github.com/gorilla/mux v1.7.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gosoon/glog v0.0.0-20180521124921-a5fbfb162a81 h1:JP0LU0ajeawW2xySrbhDqtSUfVWohZ505Q4LXo+hCmg=
github.com/gosoon/glog v0.0.0-20180521124921-a5fbfb162a81/go.mod h1:1e0N9vBl2wPF6qYa+JCRNIZnhxSkXkOJfD2iFw3eOfg=
Enable go module function
(1) go edition >= v1.11
(2) Set up GO111MODULE environment variable
To use go module First, set GO111MODULE=on,GO111MODULE There are three values ,off、on、auto,off and on That is, close and open ,auto Will be based on whether there is go.mod File to determine whether to use modules function . No matter which mode you use ,module The function is not in by default GOPATH Find dependent files in the directory , So use modules Please set up the agent .
In the use of go module when , take GO111MODULE The global environment variable is set to off, Turn it on when it needs to be used , Avoid accidentally introducing... Into existing projects go module.
Use go module function
For new projects, use go module:
go mod init github.com/ author / Project name
Build the project
go build hello.go
First you need to use go mod vendor Download all the dependencies of the project to the local vendor Directory and compile .
Such as adding import
package main
import . "fmt"
import "github.com/google/uuid"
func main() {
Println("helloword")
uuid:=uuid.New()
Println(uuid)
}
Carry out orders ( Automatically download to vendor Catalog )
F:\code\go\helloworld>go mod vendor
go: finding module for package github.com/google/uuid
go: downloading github.com/google/uuid v1.1.1
go: found github.com/google/uuid in github.com/google/uuid v1.1.1
go.mod There is an additional line of dependency in
github.com/google/uuid v1.1.1
go.sum Many more
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
Use Go Other package management tools for godep、govendor、glide、dep You can't avoid climbing over the wall ,Go Modules Is the same , But in go.mod Can be used in replace Replace a specific library with another library :
replace (
golang.org/x/text v0.3.0 => github.com/golang/text v0.3.0
)
You can also use the alicloud image station :
go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/
Or set environment variables
export GOPROXY=https://mirrors.aliyun.com/goproxy/
go grammar
Variable definitions
Common variables
package main
import "fmt"
type byte int8 // Define a new type byte
type byteAlias = int8 // Define an alias to point to int8 The actual type is still int8
func main() {
var i, k int = 10, 100
var ife bool = false
i = 100
j := 100.5 // The new variable is used to judge the type according to the value := It has to be var keyword The subsequent assignment still uses =
j = 100.6
fmt.Print(i + k)
fmt.Print(ife)
fmt.Println(j)
ks := &i // Reference point Changed ks It is equivalent to changing i
*ks = 10
fmt.Println(*ks, i)
const js int = 100 // Constant
fmt.Println(js)
const (
a = iota // One quote adds up to one The first is 0
b = iota //1
c = iota //2
)
fmt.Println(a, b, c)
var an byte = 1
fmt.Printf("%T\n", an) // The type is main.byte
var an1 byteAlias = 1
fmt.Printf("%T\n", an1) // The type is int8
}
Structures and interfaces
package main
import "fmt"
/** Structs are similar to classes */
type User struct {
userName string
userEmail string
userSex int
}
/** Defining interfaces , Defining method parameters is string The return value of type is int type */
type Phone interface {
call(string) int
}
/** Define the implementation structure */
type Iphone struct {
}
/** Iphone Realization call Method */
func (iphone Iphone) call(message string) int {
fmt.Println("iphone Said the :" + message)
return 1
}
func main() {
user := User{
"zs", "[email protected]", 0}
fmt.Println(user.userEmail)
user1 := User{
userEmail: "[email protected]"}
fmt.Println(user1.userEmail)
phone := new(Iphone)
phone.call("helloworld")
}
character string
package main
import (
"fmt"
"strings"
)
func main() {
// String cutting
str := "a_b_c"
var result []string = strings.Split(str, "_")
fmt.Println(result)
// The string contains
fmt.Println(strings.Contains(str, "c"))
// String in another string position , Subscript from 0 Start
fmt.Println(strings.Index(str, "_"))
// Compare strings Equal return 0 a<b return -1 a>b return 1
fmt.Println(strings.Compare(str, "a_b"))
// Returns the number of occurrences of a string
fmt.Println(strings.Count(str, "_"))
// Find the position of the last matching character
fmt.Println(strings.LastIndex(str, "_"))
// Whether it begins with a character
fmt.Println(strings.HasPrefix(str, "a_"))
// Whether a character ends
fmt.Println(strings.HasSuffix(str, "a_"))
//join Array elements are spliced into sep Lattice string
//[ length ] Defines an array of specified length ,... Determine the length according to the value
var strlist = []string{
"a", "b"}
var strlist1 = [...]string{
"a", "b"}
var strlist2 [2]string
strlist2[0] = "zs"
strlist2[1] = "ls"
cc := strings.Join(strlist, ",")
fmt.Println(cc, strlist1)
// How many times to replace a string with the target string
fmt.Println(strings.Replace(str, "_", "-", strings.Count(str, "_")))
// Convert case
fmt.Println(strings.ToUpper(str), strings.ToLower(str))
// Remove left and right spaces , Remove the specified character
fmt.Println(strings.TrimSpace(" a b "), strings.TrimLeft("_abc_", "_"))
// Intercepting string From start index to end index , Include the beginning but not the end .
fmt.Println(str[1:2])
}
Array
package main
import "fmt"
func main() {
var k string = "a"
// Initialize with value
var arr = [...]string{
"zs", "ls"}
arr1 := []string{
"zs", "ls"}
arr2 := [2]string{
"zs", "ls"}
fmt.Println(k, arr, arr1, arr2)
// Define only and do not initialize
var arr3 [3]string
arr3[0] = "zs"
// Modify the array value
arr3[1] = "ls"
fmt.Println(arr3)
// Get array value
fmt.Println(arr3[1])
// Get array length
fmt.Println(len(arr3))
// Circular array
for i := 0; i < len(arr3); i++ {
fmt.Println(i, arr3[i])
}
}
section
package main
import "fmt"
func main() {
// You can define slices by declaring an array of unspecified size :
var idList []int
// Defining slices
numbers := []int{
0, 1, 2, 3, 4, 5, 6, 7, 8}
// Additional numbers and 10 Into a new slice ,bumbers It doesn't change in itself
idList = append(numbers, 10)
fmt.Println(numbers)
fmt.Println(idList)
/* Create slices numbers1 Twice the capacity of the previous slice */
numbers1 := make([]int, len(numbers), (cap(numbers))*2)
/* Copy numbers Content to numbers1 */
copy(numbers1, numbers)
fmt.Println(numbers1)
}
map
package main
import "fmt"
func main() {
//var map_variable map[key_data_type]value_data_type
kvs := map[string]string{
"id": "1", "name": "zs"}
fmt.Println(kvs)
a := 1
var b int = 10
for k, v := range kvs {
fmt.Println(k, v)
}
}
Linked list list
package main
import (
"container/list"
"fmt"
)
func main() {
// A list is a non contiguous storage container , It consists of multiple nodes , Nodes record their relationship with each other through some variables , There are many ways to implement lists , Such as single chain list 、 Double linked list, etc .
userList:=list.New()
userList.PushBack("zs")
userList.PushFront("ls")
fmt.Println(userList.Len())
for i:=userList.Front();i!=nil;i=i.Next(){
fmt.Println(i.Value)
}
}
Process control
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
in := bufio.NewReader(os.Stdin)
str, _, err := in.ReadLine()
if err != nil {
fmt.Println(err.Error())
}
if string(str) == "1" {
fmt.Print("boy")
} else {
fmt.Println("girl")
}
}
loop
package main
import "fmt"
func main() {
// Initialize with value
var arr = [...]string{
"zs", "ls"}
// Circular array
for i := 0; i < len(arr); i++ {
fmt.Println(i, arr[i])
}
//range Be similar to foreach Parameters 1 Is an index parameter 2 Refer to , You don't need a value to use _ , Commonly used in map type
for index, value := range arr {
fmt.Println(index, value)
}
for _, value := range arr {
fmt.Println(value)
}
// condition loop , Print 1-10 All odd numbers
i := 0
for i < 10 {
i++
if i%2 == 0 {
continue
}
fmt.Printf("%v ", i)
}
fmt.Println()
i = 0
LOOP:
for i < 10 {
i++
if i%2 == 0 {
goto LOOP // Equivalent to continue, It can also be defined anywhere label According to logic goto
}
fmt.Printf("%v ", i)
}
}
function
package main
import "fmt"
//func function_name( [parameter list] ) [ return type ] {
func add(i int, j int) int {
return i + j
}
func calc(i int, j int) (int, int) {
return i + j, i - j
}
func main() {
fmt.Println(add(100, 34))
addresult, minusResult := calc(100, 34)
fmt.Println(addresult, minusResult)
}
exception handling
package main
import (
"errors"
"fmt"
)
/** error Interface definition of type error interface { Error() string } */
/** Generally, you can add an error parameter to the last parameter of the function , adopt errors.New establish */
func div(num1 int,num2 int) (int,error){
if(num2==0){
return 0,errors.New(" The divisor cannot be zero 0")
}
return num1/num2,nil
}
/** Custom exception , such as */
type Sex struct {
sex int;// Gender can only be 0 and 1
}
func (sex Sex) Error() string{
return fmt.Sprintf(" Gender field %v Only for 0 and 1", sex.sex)
}
func setSex(sex Sex)(string){
if(sex.sex!=1 && sex.sex !=0){
return sex.Error();
}
return ""
}
func main() {
result,err:=div(100,0)
if(err!=nil){
fmt.Println(err)
}else{
fmt.Println(result)
}
sex:=Sex{
2}
errorMsg:=setSex(sex)
fmt.Println(errorMsg)
}
边栏推荐
- 微信小程序wx.getLocation定位错误信息汇总
- Introduction to air code signature and publisher identifier
- Morsel driven parallelism: a NUMA aware parallel query execution framework
- Here comes the era of metaltc2.0
- IP address division and subnet
- Lucene构建索引与执行搜索小记
- CSV file reading (V3 & V5)
- XML modeling
- “Ran out of input” while use WikiExtractor
- Swagger basic use quick start
猜你喜欢

SSL证书安装后网站还是显示不安全

JVM basic theory.

【IT】福昕pdf保持工具選擇

Interpretation of join method in thread

Gstreamer应用开发实战指南(一)

Gstreamer应用开发实战指南(四)

IP address division and subnet

SSL证书包含了哪些信息?

After the SSL certificate is installed, the website still shows insecurity

Ffmpeg pulls webrtc streams, and the first all open source solution in the metartc industry is coming
随机推荐
“Ran out of input” while use WikiExtractor
Leetcode 1037.有效的回旋镖
Interview process and thread
Yolov5-6.0 series | yolov5 module design
Fundamentals of deep learning: face based common expression recognition (2) - data acquisition and collation
redis 缓存雪崩、穿透、击穿问题
Mysql5.7 one master multi slave configuration
Data summit 2022 conference information sharing (23 in total)
Alibaba cloud AI training camp - SQL basics 3: complex query methods - views, subqueries, functions, etc
In latex, \cdots is followed by a sentence. What's wrong with the format of the following sentence.
Some concepts in network planning
How to monitor JVM GC
Swift 扩展
arthas-boot
SSL证书安装后网站还是显示不安全
Seaweedfs client adapts to the higher version of seaweedfs service
Leetcode 929. Unique email address
Record rsyslog lost logs
Mysql5 available clusters
Practical guide to GStreamer application development (IV)