search
HomeBackend DevelopmentGolangAn article to help you understand the basic functions of Go language (Part 1)

Why we need functions

Functions are called functions in all programming languages, including Java, PHP, Python, JS, etc. They are all called functions.

The role of a function

is generally described as follows: a function can encapsulate repeated or specific functions into a convenient thing.

Note:In Go, functions support closures of.

When the function is not used

Code

package main


import "fmt"


func main() {
    //模拟一个打开文件,写入一行内容进入文件,在关闭文件的功能
    var file_name = "a.txt" //文件名
    var w_content = "爱我中华"  //写入的内容
    fmt.Println(fmt.Sprintf("打开 %s 文件",file_name))
    fmt.Println(fmt.Sprintf("向 %s 文件写入了 %s ", file_name, w_content))
    fmt.Println(fmt.Sprintf("关闭 %s 文件",file_name))


    //如果再再向其他文件写入内容,还需要复制一次


    var file_name2 = "b.txt" //文件名
    var w_content2 = "中国威武"  //写入的内容
    fmt.Println(fmt.Sprintf("打开 %s 文件",file_name2))
    fmt.Println(fmt.Sprintf("向 %s 文件写入了 %s ", file_name2, w_content2))
    fmt.Println(fmt.Sprintf("关闭 %s 文件",file_name2))
}

Use After the function,

encapsulates the same function into a function.

package main


import "fmt"


func w_file(filename string, w_content string) {
    fmt.Println(fmt.Sprintf("打开 %s 文件", filename))
    fmt.Println(fmt.Sprintf("向 %s 文件写入了 %s ", filename, w_content))
    fmt.Println(fmt.Sprintf("关闭 %s 文件", filename))
}
func main() {
    //将相同功能封装成函数
    w_file("a.txt", "爱我中华")
    w_file("b.txt", "中国威武")
}

The results of executing the above code are as follows

An article to help you understand the basic functions of Go language (Part 1)

##ps:But it can be clearly seen that by using functions to extract the same functions, the code will become simpler and neater.


Function usage

Function name naming rules

Try to name functions in camel case, for example: getName, connectData, etc. .

Syntax

In Go, the function language is defined using func Keywords.

func 函数名([参数1 参数类型1,参数2 参数类型2,...]) [(返回值 返回值类型,...)]{
    逻辑代码
}
//中括号表示可选参数

无参数,无返回值

package main


import "fmt"


func say1() {
    fmt.Println("我终于会说话了...")
}

有参数,无返回值

func say2(c string) {
    fmt.Println("我终于会说" + c + "了")
}

有或者无参数,有返回值

func say3(c string) (string) {
    fmt.Println("我终于会说" + c + "了")
    return "哦耶"
}

main函数

func main() {
    say1()
    say2("你好哇")
    result := say3("你好哇")
    fmt.Printf(result)
}

结果

An article to help you understand the basic functions of Go language (Part 1)

调用函数

函数名+括号调用函数,如果有参数传入相关参数即可。

package main


import "fmt"


func say() string{
    fmt.Println("我终于会说话了...")
    return ""
}


func main() {
    //函数名+括号调用函数
    say() //结果:我终于会说话了...
}

注:如果函数有返回值,可以不接收。

函数参数特性

在Go中,如果函数参数都是统一类型,可以这样写。

//arg1, arg2, arg3, arg4参数类型都是string
func say(arg1, arg2, arg3, arg4 string) {
  fmt.Println("我终于会说话了...")
}


//arg1,arg2参数是int类型,arg4,arg4是string类型,
func say(arg1, arg2, int, arg3, arg4 string) {
  //表示arg1, arg2, arg3, arg4参数类型都是string
  fmt.Println("我终于会说话了...")
}

大概意思就是,如果参数不写类型,会以后面碰到的类型为准。

函数的...参数

...参数,也叫可变长参数,有点像Python中的*args

功能是当不知道接收多少个参数时,接收多的参数会放在...中。

...参数需要放在最后面。

代码

package main


import "fmt"


func say(name string, content ...string) {
    fmt.Println(content)        //结果:[666 双击 ok 哦耶]
  fmt.Printf("%T\n", content) //结果:[]string,是切片类型
  fmt.Println("我是"+name, "我说了:")
  //循环切片
  for _, v := range content {
    fmt.Println(v)
  }


}


func main() {
  //函数名+括号调用函数
  say("张三", "666", "双击", "ok", "哦耶") //结果:我终于会说话了...
}

结果如图所示

An article to help you understand the basic functions of Go language (Part 1)

注:参数是...类型的,他的值是一个切片类型。

函数的返回值

返回值是一个的

package main


import "fmt"


//返回值是一个
func say1() string {
  return "ok"
}

返回值是多个的,需要用括号括起来

//返回值是多个的,需要用括号括起来
func say2() (int, string) {
  return 1, "ok"
}

返回值是命名的

//返回值是命名的,不管是多个返回值还是一个返回值,都需要括号
//如果是命名返回值,需要在逻辑代码中,将变量赋值
func say3() (a int, b string) {
  //逻辑代码
  a = 18
  b = "666"
  /*
    直接return即可,不需要retrun a,b
    return的默认就是 a 和 b
    不用跟上述返回一样,返回具体值
  */
  return
}

main函数

func main() {
  s := say1()
  fmt.Println(s)
  a1, b1 := say2()
  fmt.Println(a1, b1)
  a2, b2 := say3()
  fmt.Println(a2, b2)
}

结果

An article to help you understand the basic functions of Go language (Part 1)

The above is the detailed content of An article to help you understand the basic functions of Go language (Part 1). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete
How to use the 'strings' package to manipulate strings in Go step by stepHow to use the 'strings' package to manipulate strings in Go step by stepMay 13, 2025 am 12:12 AM

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Go strings package: how to improve my code?Go strings package: how to improve my code?May 13, 2025 am 12:10 AM

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

What are the most useful functions in the GO bytes package?What are the most useful functions in the GO bytes package?May 13, 2025 am 12:09 AM

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Mastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMay 13, 2025 am 12:07 AM

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

Go 'bytes' package quick referenceGo 'bytes' package quick referenceMay 13, 2025 am 12:03 AM

ThebytespackageinGoiscrucialforhandlingbyteslicesandbuffers,offeringtoolsforefficientmemorymanagementanddatamanipulation.1)Itprovidesfunctionalitieslikecreatingbuffers,comparingslices,andsearching/replacingwithinslices.2)Forlargedatasets,usingbytes.N

Mastering Go Strings: A Deep Dive into the 'strings' PackageMastering Go Strings: A Deep Dive into the 'strings' PackageMay 12, 2025 am 12:05 AM

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

'encoding/binary' Package in Go: Your Go-To for Binary Operations'encoding/binary' Package in Go: Your Go-To for Binary OperationsMay 12, 2025 am 12:03 AM

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Go Byte Slice Manipulation Tutorial: Mastering the 'bytes' PackageGo Byte Slice Manipulation Tutorial: Mastering the 'bytes' PackageMay 12, 2025 am 12:02 AM

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor