34

A Tour of Go: Basics 1

 5 years ago
source link: https://studygolang.com/articles/15285?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Packages, variables and functions

Packages

packages中,以大写字母开头的name是exported name,当import package时,只有exported name可以被从外部访问。

Functions

同type的连续参数可以只在最后指明type。

函数可以有多个返回值。

func swap(x, y string) (string, string) {
        return y, x
}

Go支持有name的返回值:

  • 函数定义时就定义好返回变量名,在函数内操作返回变量。
  • 用naked return语句返回。
func split(sum int) (x, y int) {
        x = sum * 4 / 9
        y = sum - x
        return
}

注意点:文中建议只在短函数中这样使用,因为长了容易影响可读性。

Variables

var关键字定义变量。

有初始值时可以省略type。

技巧及注意点:

  • 在函数内,可以使用:=符号替换有初始值的变量定义。
  • 但是在函数外,所有语句必须以关键字开始,所以不能使用:=符号。

Basic types

bool
string
int  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptr
byte // alias for uint8
rune // alias for int32
        // represents a Unicode code point
float32 float64
complex64 complex128

技巧:

  • var和import都可以用小括号声明多个包或变量。
  • 文中建议,如无特殊需求,使用int就好,不必指明size或sign。

变量定义时,如不指定初始值,则分配对应type的默认值。

  • numeric type: 0
  • bool: false
  • string: ""

表达式T(v)表示将值v转换成T类型:

var i = 10
var f = float64(i)

注意点:与C语言不同,Go必须显式转换。

常量定义将var换成const关键字即可,不过不能使用:=符号。

疑问

  1. Numeric constants are high-precision values.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK