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

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.

主站蜘蛛池模板: 金堂县| 巴里| 扶风县| 云和县| 黑河市| 河北省| 怀仁县| 西宁市| 梨树县| 泰和县| 石阡县| 桐梓县| 赫章县| 晋中市| 巴东县| 靖远县| 南澳县| 周至县| 余干县| 延长县| 依安县| 曲阜市| 洛南县| 时尚| 法库县| 漳浦县| 汤阴县| 工布江达县| 濮阳县| 泗水县| 怀宁县| 方山县| 靖远县| 团风县| 米脂县| 昭通市| 灌阳县| 津市市| 平乐县| 内江市| 临澧县|