首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Golang: Functions

Golang: Functions

作者头像
Miigon
发布2022-10-27 15:54:31
发布2022-10-27 15:54:31
2870
举报
文章被收录于专栏:Miigon's BlogMiigon's Blog

Functions

Reader of this blog is assumed to have some basic programming skills. So in this series, we will not get into basic things like how function works. Because it’s basically the same for every languages, including Go.

Instead, we will focus on comparing the same feature in Go and in C++ and see where the differences are.

Declaration

Here’s a Go function declaration:

代码语言:javascript
复制
func add(x int, y int) int {
	return x + y
}

Noted that in Go, type comes after variable/function name, which is different from all the other “C-like” languages, eg. C, C++, C#, Java.

Unique syntaxes and syntax sugars

1. Writing type only once for consecutive names with the same type

代码语言:javascript
复制
x int, y int

// can be written as

x, y int

The same works for function parameters as well:

代码语言:javascript
复制
func add(x int, y int) int { return x + y }

// can be written as

func add(x, y int) int { return x + y }

2. Multiple return value

代码语言:javascript
复制
func split(sum int) (int, int) {
	x := sum * 4 / 9		// short variable declaration
	return x, sum - x		// return two values
}

3. Named return value

The above example can be written like this:

代码语言:javascript
复制
func split(sum int) (x int, y int) {  // give names to our return values.
	x = sum * 4 / 9			// assign return value just like you would a normal variable
	y = sum - x				// use `x` like an ordinary variable
	return					// return all values assigned before
}

you can also omit consecutive identical types except for the last one: (just like variables)

代码语言:javascript
复制
func split(sum int) (x, y int) { // <-- notice here
	x = sum * 4 / 9
	y = sum - x
	return
}

Once you assigned all the return values, do a simple return without anything after it, Go will help you return all the values you assigned before.

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • Functions
    • Declaration
    • Unique syntaxes and syntax sugars
      • 1. Writing type only once for consecutive names with the same type
      • 2. Multiple return value
      • 3. Named return value
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档