Skip to content
gqlxj1987's Blog
Go back

Golang Tips

Edit page

这里列举一些golang的一些小技巧

Behavior Of Missing The OK Optional Return Value

Basic Rule:

Whether or not the ok return value is present will not affect program behavior.

Exception:

Missing the ok optional return value will make current goroutine panic if a type assertion fails.


var v interface{} = "abc"
_, ok = v.(int) // will not panic
_ = v.(int)     // will panic!

这里提供了一种思路,在interface的转化部分


var m = map[int]int{}
_, ok = m[123] // will not panic
_ = m[123]     // will not panic

关于第二句?

Types Of Values

Basic Rule:

Values should have either a type or a default type.

Exception:

Untyped nil has neither a type nor a default type.


var v interface{} 
fmt.Printf("type of %v is %T \n", v, v) // type of <nil> is <nil>
var _ interface{} = v.(interface{}) // will panic

注意inteface的default value是nil

The Blank Composite Literals

If a type T support composite literal values, then T{} is its zero value.

For a map or a slice type T, T{} isn’t its zero value. Its zero value is represented with nil.

Comparison

Most types in Go support comparison.

Map, slice and function types don’t support comparison. but, Map, slice and function values can be compared to the nil identifier.

Modify Unaddressable Values

Unaddressable values can’t be modified.

Although map element values are unaddressable, but their value can be modified if their types are numeric or string types.

主要是针对map部分?


var mt = map[string]T{"abc": {123}}
	_ = mt
// mt["abc"].x *= 2 // error: mt["abc"].x is not changeable
mt["abc"] = T{mt["abc"].x * 2} // map elements are unaddressable
                               // but replaceable
	

随着带来的问题

Map elements are not addressable, even if they can be overwritten.

map的value可以改写,但是无法给出地址


Edit page
Share this post on:

Previous Post
GraphQL
Next Post
Design Scale System