IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Go语言的变量定义

    nanxiao发表于 2015-12-21 05:57:01
    love 0

    以下摘自The Go Programming Language:

    A var declaration creates a variable of a particular type, attaches a name to it, and sets its initial value. Each declaration has the general form
    var name type = expression
    Either the type or the = expression part may be omitted, but not both. If the type is omitted, it is determined by the initializer expression. If the expression is omitted, the initial value is the zero value for the type, which is 0 for numbers, false for booleans, “” for strings, and nil for interfaces and reference types (slice, pointer, map, channel, function). The zero value of an aggregate type like an array or a struct has the zero value of all of its elements or fields.

    short variable declarations are used to declare and initialize the majority of local variables. A var declaration tends to be reserved for local variables that need an explicit type that differs from that of the initializer expression, or for when the variable will be assigned a value later and its initial value is unimportant:
    i := 100 // an int
    var boiling float64 = 100 // a float64
    var names []string
    var err error
    var p Point

    关于“A var declaration tends to be reserved for local variables that need an explicit type that differs from that of the initializer expression,”的理解:var boiling float64 = 100如果使用i := 100的形式来定义,则会认为i是int,而不是float。



沪ICP备19023445号-2号
友情链接