A function is a block of statements that can be used repeatedly in a program.
A function will not execute automatically when a page loads.
A function will be executed by a call to the function.
To create (often referred to as declare) a function, do the following:
func
keyword.
func
FunctionName() {
// code to be executed
}
Functions are not executed immediately. They are "saved for later use", and will be executed when they are called.
In the example below, we create a function named "myMessage()". The opening curly brace ( { ) indicates the beginning of the function code, and the closing curly brace ( } ) indicates the end of the function. The function outputs "I just got executed!". To call the function, just write its name followed by two parentheses ():
package main
import ("fmt")
func myMessage() {
fmt.Println("I just got executed!")
}
func main() {
myMessage() // call the function
}
Result:
I just got executed!
A function can be called multiple times.
package main
import ("fmt")
func myMessage() {
fmt.Println("I just got executed!")
}
func main() {
myMessage()
myMessage()
myMessage()
}
Result:
I just got executed!
I just got executed!
I just got executed!
A-z
, 0-9
, and _
)Tip: Give the function a name that reflects what the function does!
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!