Mastering Functions in Go: From Basics to Advanced Usage
This article introduces Go functions, explaining why they’re essential, how to define and call them, parameter and return value variations—including variadic arguments—and demonstrates clean code refactoring with practical examples and output screenshots.
Preface
Hey everyone, I'm 星期八, and we continue learning Go basics—functions.
Why Functions Are Needed
Functions exist in all programming languages such as Java, PHP, Python, JS, and they encapsulate repeated or specific functionality for easy reuse.
Purpose of Functions
Functions package repeated or specific tasks into a callable unit.
Note: In Go, functions support closures .
Code Without Functions
package main
import "fmt"
func main() {
// Simulate opening a file, writing a line, and closing the file
var file_name = "a.txt" // file name
var w_content = "爱我中华" // content to write
fmt.Println(fmt.Sprintf("打开 %s 文件", file_name))
fmt.Println(fmt.Sprintf("向 %s 文件写入了 %s ", file_name, w_content))
fmt.Println(fmt.Sprintf("关闭 %s 文件", file_name))
// Writing to another file requires duplicate code
var file_name2 = "b.txt" // file name
var w_content2 = "中国威武" // content to write
fmt.Println(fmt.Sprintf("打开 %s 文件", file_name2))
fmt.Println(fmt.Sprintf("向 %s 文件写入了 %s ", file_name2, w_content2))
fmt.Println(fmt.Sprintf("关闭 %s 文件", file_name2))
}Code Using Functions
Encapsulate the same functionality 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() {
// Reuse the function for different files
w_file("a.txt", "爱我中华")
w_file("b.txt", "中国威武")
}The execution results are shown below:
ps: Using functions makes the code simpler and cleaner.
Function Usage
Naming Conventions
Function names should use camelCase, e.g., getName, connectData.
Syntax
In Go, functions are defined with the func keyword.
func functionName([param1 type1, param2 type2, ...]) [ (returnType1, returnType2, ...) ] {
// logic
}No Parameters, No Return Values
package main
import "fmt"
func say1() {
fmt.Println("我终于会说话了...")
}With Parameters, No Return Values
func say2(c string) {
fmt.Println("我终于会说" + c + "了")
}With Parameters and Return Values
func say3(c string) (string) {
fmt.Println("我终于会说" + c + "了")
return "哦耶"
}main Function
func main() {
say1()
say2("你好哇")
result := say3("你好哇")
fmt.Printf(result)
}Result:
Calling Functions
Invoke a function by writing its name followed by parentheses; provide arguments if needed.
package main
import "fmt"
func say() string {
fmt.Println("我终于会说话了...")
return ""
}
func main() {
// Call the function
say() // Output: 我终于会说话了...
}Note: If a function returns a value, you may ignore it.
Function Parameter Features
When all parameters share the same type, you can declare them together.
// All parameters are strings
func say(arg1, arg2, arg3, arg4 string) {
fmt.Println("我终于会说话了...")
}
// Mixed types: first two are int, last two are string
func say(arg1, arg2 int, arg3, arg4 string) {
fmt.Println("我终于会说话了...")
}If a parameter type is omitted, Go infers it from the subsequent typed parameter.
Variadic Parameters (...)
Variadic parameters (…args) allow a function to accept an arbitrary number of arguments; they must appear last.
func say(name string, content ...string) {
fmt.Println(content) // e.g., [666 双击 ok 哦耶]
fmt.Printf("%T
", content) // []string, a slice type
fmt.Println("我是" + name, "我说了:")
for _, v := range content {
fmt.Println(v)
}
}
func main() {
say("张三", "666", "双击", "ok", "哦耶")
}Result:
Note: A variadic parameter is received as a slice.
Function Return Values
Single Return Value
func say1() string {
return "ok"
}Multiple Return Values
func say2() (int, string) {
return 1, "ok"
}Named Return Values
func say3() (a int, b string) {
a = 18
b = "666"
return
}main Function
func main() {
s := say1()
fmt.Println(s)
a1, b1 := say2()
fmt.Println(a1, b1)
a2, b2 := say3()
fmt.Println(a2, b2)
}Result:
Summary
We have covered Go functions, including definition, calling, parameters, variadic arguments, and return values. Feel free to leave questions in the discussion area.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
