2016-02-22 23 views
0

我是一名正在學習Go的Python開發人員,正在編寫一個簡單的單鏈表實現作爲練習。幾年前我在Python中完成了這個工作,現在正在使用Go進行復制。Golang Python中'is`的等價操作符

作業中的一種方法(我最初在學校做過)是remove(node):從列表中刪除給定的節點。在Python中,我使用了is運算符。類似這樣的:

def remove(self, node): 
    element = self.head 
    prev = None 
    while element: 
     if element is node: 
      remove node form list... 
     prev = element 
     element = element.next 

在Python中,is運算符檢查身份。因此,例如

>>> class Foo(object): 
...  def __init__(self, x): 
...   self.x = x 
... 
>>> foo = Foo(5) 
>>> bar = Foo(5) 
>>> baz = foo 
>>> foo is baz 
True 
>>> foo is bar 
False 

即使在實例foobar的值是相同的,他們是不是同一個對象,我們在這裏看到:

>>> id(foo) 
139725093837712 
>>> id(bar) 
139725093837904 

然而foobaz是同一個對象:

>>> id(foo) 
139725093837712 
>>> id(baz) 
139725093837712 

我該怎麼去做同樣的事情在Go?等於運算符,==,僅僅檢查的值是相同的:

package main 

import "fmt" 

type Test struct { 
    x int 
} 

func main() { 
    a := Test{5} 
    b := Test{5} 
    c := Test{6} 

    fmt.Println("a == b", a == b) 
    fmt.Println("a == c ", a == c) 
    fmt.Println("b == c ", a == c) 
} 

,輸出:

a == b true 
a == c false 
b == c false 

Playground link

ab具有相同的價值,但不是同一個對象。 Go有沒有類似Python的方法來檢查身份?還是有一個可用的包或某種方式來推出自己的身份檢查功能?

+2

比較指針也許? – khuderm

回答

5

你在說什麼需要在Go中使用指針。在您的Python代碼中,foo,bar和baz包含對對象的引用,因此您可以討論它們中的兩個是否引用相同的基礎對象。在你的Go代碼中,a,b和c是Test類型的變量。如果你將它們聲明爲Test(* Test)的指針,你會看到不同的東西。試試這個:

package main 

import "fmt" 

type Test struct { 
    x int 
} 

func main() { 
    // a, b, and c are pointers to type Test 
    a := &Test{5} 
    b := &Test{5} 
    c := a 

    fmt.Println("a == b", a == b)  // a and b point to different objects 
    fmt.Println("a == c", a == c)  // a and c point to the same object 
    fmt.Println("*a == *b", *a == *b) // The values of the objects pointed to by a and b are the same 
} 
+2

關於鏈接列表的具體應用:標準['container/list'](https://golang.org/src/container/list/list.go)是一個雙向鏈表,因此並不完全與提問者相同的情況,但它使用指針比較,例如它的'func Next()'。 – twotwotwo