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

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.

主站蜘蛛池模板: 炉霍县| 新田县| 沙田区| 磐安县| 阿克苏市| 邵阳县| 江永县| 从化市| 安乡县| 永春县| 新乡县| 常宁市| 厦门市| 丹阳市| 鸡泽县| 芒康县| 襄城县| 西贡区| 潼南县| 苏尼特右旗| 文山县| 鹤峰县| 牙克石市| 宁南县| 绥棱县| 大渡口区| 高雄县| 辽源市| 博白县| 平顺县| 玉林市| 咸阳市| 营口市| 分宜县| 柳州市| 枣庄市| 平塘县| 土默特左旗| 乐至县| 黑龙江省| 和硕县|