Variables in Go

Introduction

Variables is the most common and useful conception in programming language. Variables in Go, of course have something same and different with other languages. Especially, as an strong type language, we won't expect using Go's variables like in Python.

In this article, we will talk about 4 things(Agenda):

- Variable declaration
- Redeclaration
- Visiblity and Naming convetions
- Type conversions

Usage(aka why we need variables)
To provide a little flexiblities to our applications, we introduce variables.

Variable declaration

扫描二维码关注公众号,回复: 8108394 查看本文章

1. There are three methods to declare a variable
a. var i int
It looks like how you read it: I am going to declare a variable call i, it's an integer.

var i int
i = 42
i = 27
fmt.Println(i)

b. var i int = 42
To keep things simple. We can combine two lines above together.

var i int = 42
fmt.Println(i)

c. i := 42
More simple than above, we let Go to figure what type this variable is. Beware, Go may figure out a type which is not our expected. For example, Go will only figure integer or float64, no float32.

2. When to use which?
1st method
We want declare a variable but we don't want to initialize it yet. Like we need an acceptor to accept a value in a loop, we can use var acceptor int.

2nd method
Go doesn't have enough infomation to fugure out what type we really want. So we can specify the type.

var i float32 = 42
fmt.Printf("%v, %T", i, i)
// output: 42, float32

3rd method

May be the most used method. We let it "Go".

3. Declare at the package level

We can not use := method at package level. It has to be var i int = 42.

But we can create a block of declaration at package level.

package main

import "fmt"

var (
    actorName string = "Elisabeth Sladen"
    companion string = "Sarah Jane Smith"
    doctorNumber int = 3
    season int = 11
)

var (
    counter int = 0
)

func main() {
    //...
}

We can use this block to design. Different variables go to different block.

Redeclaration

1. We can declare a variable at package level and at function level again.

package main

import "fmt"

var i int = 27

func main() {
    fmt.Println(i) 
    var i int = 42
    fmt.Println(i)
} 
// output
// 27 
// 42 

This is also called "shadowing".

2. Varibales in Go have to be used
This feature can keep our Go application nice & clean. Especially when our application run for a long time and/or redesign many time, our application may have many invail variables but we are unkonwn.

Visiblity and Nameing convetions

1. How nameing controls visiblity in Go
Lower case first letter variables are scoped to the package. Other package comsume this package can't see this kind of variables.
Upper case first letter variables are explosed to the outside world.

There are thress levels of visiblity in Go:
Lower case varibales: Scoped inside the package.
Upper case varibales: Explosed to the outside world.
Block scoped: scoped inside a function.

2. Naming conventions

a. The length of the variable name, should reflect the life span of the variable
For example, for-loop i, counter, length of the name is short and the life span of the variable is short. The amount of time we keep the meaning of variable name in our head is also small.
Keep the name variable as short as possible but also reflect the life span of it.

Good Example:

var seasonNumber int = 11

b. Common abbreviation should be all upper case.
For example: theURL, theHTTP, ...
var theHTTPRequest string = "www.google.com"

Type conversions

1. Using int(), float32(), ... as a function to converse type. They are called conversion functions.
Beware some converstions may loss information.
For example:

var i float32 = 42.5
var j int
j = int(i)
// j output : 42

2. Go won't risk the posibility the lost infomation in conversion by itself.
So if we need it, we will specify with convention functions.
For example:

var i float32 = 42.5
var j int
j = i
// Compile Error
// No Python style conversion 

3. Convert a integer to a string
Using a string() conversion function may result strange.

package main

import (
        "fmt"
)


func main() {
    var i int= 42
    fmt.Printf("%v, %T\n", i, i)

    var j string
    j = string(i)
    fmt.Printf("%v, %T", j, j)
}
// output
// 42, int
// *, string 

In Go, string is alias to string mode bytes. When we use convert function string(), it's looking what 42 represent in unicode(ASCII). That is *. FYI we can try: 43 is +.

So in this task, we need a package named "strconv".

package main

import (
        "fmt"
        "strconv"
)


func main() {
    var i int= 42
    fmt.Printf("%v, %T\n", i, i)

    var j string
    j = strconv.Itoa(i)
    fmt.Printf("%v, %T", j, j)
}
// output
// 42, int
// 42, string         

Summary

Variable declaration.
int foo int // declare and initialize later
int foo int = 42 // declare and initialize at the same time
foo := 42 // short hand. declare and initialize at the same time, letting Go decides the type

Can't redeclare a variables, but can shadow them.

All variables must be used.(Our code is envolving. This is nice and helpful.)

Visiblity
Lowe case first letter for package scope.
Upper case first letter to export.

Naming conversions
Pascal or camelCase
- Except: Capitalize acronyms(HTTP, URL, ...)
As shor as possible
- longer names for longer lives

Type conversions
- destinationType(variable)
- use strconv package for strings

猜你喜欢

转载自www.cnblogs.com/drvongoosewing/p/12003879.html