名称和值 – Go vs Python

huangapple go评论100阅读模式
英文:

Name & value - Go vs Python

问题

在Python中,使用以下代码:

x = 3
x = 'str'

允许x首先指向int类型的对象,然后指向str类型的对象,因为Python是动态类型的。type(x)给出的是值(3str)的类型,而不是名称x的类型。

实际上,x并不存储值3,而是指向值为3int类型对象。


在GO语言中,使用以下语法:

func main() {
    y := 2
    fmt.Println(reflect.TypeOf(y)) // 输出'int'
    y = "str" // 编译时错误,因为GO是静态类型的
}

问题:

int是名称y的类型还是值2的类型?

英文:

In python, with below code,

x = 3
x='str'

allows x to first point to int type object and then to str type object, because python is dynamic typed. type(x) gives type of value(3 or str) but not type of name x.

In-fact, x does not store value 3 but point to int type object whose value is 3


In GO language, with below syntax,

func main() {
        y := 2
        fmt.Println(reflect.TypeOf(y)) // gives 'int'
        y = "str" // Compile time error, because GO is static typed 
}

Question:

Is int, the type of name y or the type of value 2?

答案1

得分: 5

Python变量绑定到在程序运行过程中动态分配给它们的类的实例上。因此,特别是对于可变对象,它们只是包含有关其数据位置和所指向数据类型的信息的指针。这就是为什么在分配新值时,你会创建一个新的实例(这是你主要关注的),并将变量名绑定到它,所以类型与相关,而不是变量本身。

>>> x = 3; id(x)
1996006560
>>> x = 'str'; id(x)
1732654458784

另一方面,Go变量(当不是指针时)作为强大的内存位置,因为该语言是编译型的,变量得到一个常量的“工作”,用于保存某种类型的信息(也可以是指针)。因此,一个变量几乎肯定会在程序中保持其内存,具有恒定的数据类型属性,并且可以说变量本身是某种类型(而不是半指针类型)。

package main
import . "fmt"
func main () {
    x := "str"; Println(&x)         // 0xc04203a1c0
    x = "Hello world!"; Println(&x) // 0xc04203a1c0
}
英文:

Python variables are bound to instances of classes that are assigned to them dynamically over the course of the program. Therefore, and especially with mutable objects, they are merely pointers who contain information about their data location and the type of the data they point to. That's why, upon assigning a new value, you are creating a new instance (which is your main interest) and bind the variable name to it, so the type is related to the value, not the variable itself.

>>> x = 3; id(x)
1996006560
>>> x = 'str'; id(x)
1732654458784

<hr>

Go variables on the other hand, are serving (when not pointers) as stronghold memory locations, as the language is compiled and the variables get a constant "job" to keep a certain type of information (which could be a pointer as well). Therefore, a variable would almost certainly maintain his memory along the program, will have constant datatype properties, and, you could say the variable itself is of a certain type (and not of a semi-pointer type).

package main
import . &quot;fmt&quot;
func main () {
	x := &quot;str&quot;; Println(&amp;x)         // 0xc04203a1c0
	x = &quot;Hello world!&quot;; Println(&amp;x) // 0xc04203a1c0
}

huangapple
  • 本文由 发表于 2017年5月4日 05:57:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/43770667.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定