官术网_书友最值得收藏!

Variables

This is a variable declaration:

var a int

It says a is an int.  That means a can contain any value that has the type int. Typical int would be like 0, 1, 2, and so on and so forth. It may seem odd to read the previous sentence, but typically is used correctly. All values of type int are typically int.

This is a variable declaration, followed by putting a value into the variable:

s := "Hello World"

Here, we're saying, define s as a string, and let the value be "Hello World". The := syntax can only be used within a function body. The main reason for this is not to cause the programmer to have to type var s string = "Hello World".

A note about the use of variables: variables in Go should be thought of as buckets with a name on them, in that they hold values. The names are important insofar as they inform the readers about the values they are supposed to hold. However, names do not necessarily have to cross barriers. I frequently name my return values with retVal, but give it a different name elsewhere. A concrete example is shown:

 func foo(...) (retVal int) { ... return retVal }
func main() {
something := foo()
...
}

I have taught programming and ML for a number of years now, and I believe that this is a hump every programmer has got to get over. Frequently students or junior team members may get confused by the difference in naming. They would rather prefer something like this:

 func foo(...) (something int) { ... return something }
func main() {
something := foo()
...
}

This is fine. However again, speaking strictly from experience, this tends to dampen the ability to think abstractly, which is a useful skill to have, especially in ML. My advice is, get used to using different names, it makes you think more abstractly.

In particular, names do not persist past what my friend James Koppel calls an abstraction barrier. What is an abstraction barrier? A function is an abstraction barrier. Whatever happens inside the function body, happens inside the function body and cannot be accessed by other things in the language. Therefore if you name a value fooBar inside the function body, the meaning of fooBar is only valid within the function.

Later we will see another form of abstraction barrier—the package.

主站蜘蛛池模板: 辽宁省| 舟曲县| 黑龙江省| 社会| 甘南县| 拉孜县| 车致| 邓州市| 苗栗市| 嘉禾县| 阿拉善左旗| 赣州市| 五原县| 寿宁县| 时尚| 婺源县| 湟中县| 吉林省| 鄱阳县| 宁明县| 腾冲县| 措勤县| 彭山县| 富蕴县| 大厂| 尼玛县| 监利县| 廊坊市| 石门县| 南木林县| 苍南县| 台北县| 石棉县| 隆化县| 嘉祥县| 无极县| 陇川县| 双辽市| 富蕴县| 庄河市| 博客|