Go語言程式:在類中使用this關鍵字
在Go程式語言中,沒有類的概念,因此使用結構體來演示在類中使用`this`關鍵字。`this`關鍵字指的是程式中當前正在執行的當前方法或物件。
在本文中,我們將使用兩個例子來了解程式的工作原理。在第一個例子中,我們將透過呼叫`this`結構體上的方法並列印其名稱和年齡來使用`Child`結構體;在第二個例子中,我們將使用`Rectangle`結構體,透過呼叫`this`結構體上的方法來列印其面積。讓我們來看一下實際實現來理解程式。
演算法
在程式中匯入`fmt`包,這將有助於輸入和輸出的格式化。
建立一個具有所需欄位的結構體。
為了演示`this`關鍵字的使用,建立一個沒有引數的方法,並在結構體上呼叫該方法。
在主函式中設定例項中的值並呼叫該方法。
當呼叫該方法時,當前例項的欄位將列印在控制檯上。
使用`fmt`包中的`fmt.Println`函式執行列印語句。
示例1
在這個例子中,我們將建立一個具有兩個欄位`Name`和`age`的`Child`結構體。在`Child`結構體上建立一個沒有引數的`greet`函式,當呼叫該方法時,其中的語句將作為輸出列印。在這裡,`c.Name`和`c.Age`將指代當前例項。讓我們看看程式碼是如何執行的。
package main import "fmt" type Child struct { Name string Age int } func (c Child) greet() { fmt.Printf("Hello, my name is %s and I'm %d years old.\n", c.Name, c.Age) } func main() { c := Child{"Veronica", 16} //set the values of the instance c.greet() //call the method }
輸出
Hello, my name is veronica and I'm 16 years old.
示例2
在這個例子中,我們建立結構體的方式與上一個例子類似。這裡,矩形的兩個欄位`width`和`height`將相乘以獲得當前例項的面積。在主函式中,當呼叫`Area()`方法時,將列印矩形的面積。讓我們看看程式碼是如何執行的。
package main import "fmt" type Rectangle struct { Width float64 Height float64 } func (rect Rectangle) Area() float64 { return rect.Width * rect.Height } func main() { rect := Rectangle{6.0, 10.0}//set the values in the instance fmt.Printf("Area of rectangle with width %.2f and height %.2f is %.2f\n", rect.Width, rect.Height, rect.Area()) //print the area of the rectangle }
輸出
Area of rectangle with width 6.00 and height 10.00 is 60.00
結論
我們使用兩個例子執行並編譯了該程式,展示了在類中使用`this`關鍵字。在第一個例子中,使用了`child`結構體;在第二個例子中,使用了`rectangle`結構體來演示`this`關鍵字的使用。這裡,它是透過在結構體上呼叫方法並列印欄位值來演示的。