当前位置:网站首页>Understand the usage of functions and methods in go language
Understand the usage of functions and methods in go language
2022-07-05 17:13:00 【1024 questions】
Function definition syntax
Function definition example
No return function
Single return function
Multiple return function
Method (Method) Definition
Method (Method) Example
Basic types
Type of structure
Function definition syntaxConsistent with most languages ,Go The function definition in language is basically consistent with that in other languages
func function_name(Parameter-list) { // function body...}func function_name(Parameter-list) Return-Type { // function body...}func function_name(Parameter-list) (Multiple Return-Types){ // function body..}
func: Function definition keywords
function_name: The name of the function ,Go Language is mainly used camel-case( hump ) Way of naming , Also according to the nature of the function , Use initial case to distinguish functions , The details will be explained in the later special chapters Go The norms of language
Parameter-list: parameter list , If nothing can be ignored
Return-Type/Multiple Return-Types: Type of return value , namely return Type of return value , Here, three forms are distinguished :
No return value / Single return value / Multiple return values
The other two are slightly different in the use of parentheses , Single return types generally do not add parentheses , For multiple return values, you need to add parentheses
In addition, for the sake of beauty , Parentheses after the parameter list , There is a space between the suggestion and the return type
Function definition example No return functionfunc HelloFunc() { fmt.Println("Hello, World")}
Single return function This example demonstrates the parameter definition method and the return value type definition method
func HelloFunc(msg string) string { return "Hello, " + msg}
Multiple return function The type of the second return value is usually used to return an error , This is convenient for the program to handle exceptions
func HelloFunc(msg string) (string, error) { return "Hello, " + msg, nil}
Let's take a look at the complete code implementation , Call in main function HelloFunc when , You also need two variables to receive the corresponding values
package mainimport "fmt"func HelloFunc(msg string) (string, error) { return "Hello, " + msg, nil}func main() { printString, err := HelloFunc("World") if err == nil { fmt.Println(printString) }}
Method (Method) Definition Go There are no classes in language , So in Go Language provides a method definition similar to function definition , By adding Reciever type , Implement the definition of a method in a similar class , Methods can be used Reciver Properties of . Let's take a look at grammar :
func (Reciever-Name Type) function_name(Parameter-list) (Multiple Return-Types){ // function body..}
Because most definitions are the same as the above function definitions , No more details here , Just introduce the new part :
Reciever-Name: The type must be a custom type , Cannot be built-in int, string etc. , Use the words , Errors will be reported at compile time
Method (Method) Example Basic typesLet's look at a method implemented by basic types , Here we use a knowledge point that we haven't learned —— Custom type type, It will be explained in detail later , Don't tangle here . The meaning of this sentence is through custom types mystring Redefined variables , Essentially with string The same type .
type mystring string
Notice our function definition here , Before the function name , More (msg mystring) The definition of , And inside the function , We can also use msg
func (msg mystring) HelloFunc() { str := "Hello, " + msg fmt.Println(str)}
And in the main When calling in a function , Different from the function call above , We use call directly mymsg Methods HelloFunc, It implements a method similar to the above example
var mymsg mystringmymsg = "World"mymsg.HelloFunc()
The full code is shown below
package mainimport "fmt"type mystring stringfunc (msg mystring) HelloFunc() { str := "Hello, " + msg fmt.Println(str)}func main() { var mymsg mystring mymsg = "World" mymsg.HelloFunc()}
Type of structure In fact, from the source code of each project , Methods are more related to structures (struct) And interface (interface) Use it together , These will be explained in detail later , All you need to know is . Here is a simple example , Let's calculate the area of the rectangle .
Defines a structure rect, It contains two attributes: length and width
How to calculate the area area(),Reciver Defined as structure type , In this way, the body , You can use length and width to calculate the area
Main function , Defines a structure , And the initialization length and width are 3 and 4
Call the r.area() Complete the area calculation
package mainimport "fmt"type rect struct { width float64 height float64}func (r rect) area() float64 { return r.width * r.height}func main() { r := rect{3, 4} rectArea := r.area() fmt.Printf("Rect area is %v\n", rectArea)}
This article is about one article Go This is the end of the article on the usage of functions and methods in language , More about Go Language function Please search the previous articles of SDN or continue to browse the related articles below. I hope you will support SDN more in the future !
边栏推荐
- goto Statement
- 网站页面禁止复制内容 JS代码
- 高数 | 旋转体体积计算方法汇总、二重积分计算旋转体体积
- The two ways of domestic chip industry chain go hand in hand. ASML really panicked and increased cooperation on a large scale
- Precision epidemic prevention has a "sharp weapon" | smart core helps digital sentinels escort the resumption of the city
- Is it safe to open an account for digging wealth stocks? How is it safe to open a stock account?
- Timestamp strtotime the day before or after the date
- npm安装
- CMake教程Step4(安装和测试)
- Copy mode DMA
猜你喜欢
兰空图床苹果快捷指令
Rider 设置选中单词侧边高亮,去除警告建议高亮
【Web攻防】WAF检测技术图谱
[first lecture on robot coordinate system]
Error in composer installation: no composer lock file present.
PHP talent recruitment system development source code recruitment website source code secondary development
dried food! Semi supervised pre training dialogue model space
Judge whether a number is a prime number (prime number)
腾讯音乐上线新产品“曲易买”,提供音乐商用版权授权
CMake教程Step1(基本起点)
随机推荐
C how TCP restricts the access traffic of a single client
Is it safe to open a securities account by mobile phone? Detailed steps of how to buy stocks
CMake教程Step2(添加库)
浏览器渲染原理以及重排与重绘
网上办理期货开户安全吗?网上会不会骗子比较多?感觉不太靠谱?
[Web attack and Defense] WAF detection technology map
Twig数组合并的写法
Is it safe for qiniu business school to open a stock account? Is it reliable?
張平安:加快雲上數字創新,共建產業智慧生態
Browser rendering principle and rearrangement and redrawing
mysql中取出json字段的小技巧
Rider 设置选中单词侧边高亮,去除警告建议高亮
Is it safe to open an account for digging wealth stocks? How is it safe to open a stock account?
PHP人才招聘系统开发 源代码 招聘网站源码二次开发
China Radio and television officially launched 5g services, and China Mobile quickly launched free services to retain users
Deeply cultivate 5g, and smart core continues to promote 5g applications
Wsl2.0 installation
C language to get program running time
Embedded UC (UNIX System Advanced Programming) -2
【jmeter】jmeter脚本高级写法:接口自动化脚本内全部为变量,参数(参数可jenkins配置),函数等实现完整业务流测试