- Hands-On Full Stack Development with Go
- Mina Andrawos
- 413字
- 2021-07-02 12:33:30
Functions – the basics
Here is how you write a function in Go:
func main(){
//do something
}
The main function is almost always the first function that gets executed in your Go program. The main function needs to live inside the main package, since main is the entry point package for your Go program.
Here is what a function with arguments would look like:
func add(a int, b int){
//a+b
}
Since the a and b arguments from the preceding code are of the same type, we can also do this:
func add(a,b int){
//a+b
}
Now, let's say we want to return a value from our function. Here is what this would look like:
func add(a,b int)int{
return a+b
}
Go also allows multiple returns, so you can do this:
func addSubtract(a,b int)(int,int){
return a+b,a-b
}
In Go, there is a concept known as named returns, which basically means that you can name your return values in the function header. Here is what this looks like:
func addSubtract(a,b int)(add,sub int){
add = a+b
sub = a-b
return
}
Functions are also first-class citizens in the Go language, which means that you can assign a function to a variable and use it as a value. Here is an example:
var adder = func(a,b int)int{
return a+b
}
var subtractor = func(a,b int) int{
return a-b
}
var addResult = adder(3,2)
var subResult = subtractor(3,2)
Because of this, you can also pass functions as arguments to other functions:
func execute(op func(int,int)int, a,b int) int{
return op(a,b)
}
Here is an example of us making use of the execute function we defined previously:
var adder = func(a, b int) int {
return a + b
}
execute(adder,3,2)
Go also supports the concept of variadic functions. A variadic function is a function that can take an unspecified number of arguments. Here is an example of an adder function that takes an unspecified number of int arguments and then adds them:
func infiniteAdder(inputs ...int) (sum int) {
for _, v := range inputs {
sum += v
}
return
}
The preceding function takes any number of int arguments and then sums them all. We'll cover the for..range syntax here later in this chapter, under the Conditional statements and loops section. We can then call our new function using the following syntax:
infiniteAdder(1,2,2,2) // 1 + 2 + 2 + 2
We'll look at how functions can be accessed from other packages in the next section.
- The Data Visualization Workshop
- SQL Server從入門到精通(第3版)
- Spring Boot實(shí)戰(zhàn)
- 算法圖解
- Delphi開發(fā)典型模塊大全(修訂版)
- Mastering HTML5 Forms
- Android移動(dòng)應(yīng)用項(xiàng)目化教程
- Go語(yǔ)言入門經(jīng)典
- Drupal 8 Development:Beginner's Guide(Second Edition)
- jQuery Mobile Web Development Essentials(Second Edition)
- 零基礎(chǔ)學(xué)編程系列(全5冊(cè))
- Android開發(fā)進(jìn)階實(shí)戰(zhàn):拓展與提升
- WCF編程(第2版)
- Learning Google Apps Script
- 軟件測(cè)試實(shí)驗(yàn)實(shí)訓(xùn)指南