Latest web development tutorials

ไปแบบภาษา

ภาษาไปให้ชนิดข้อมูลอื่นที่เป็นอินเตอร์เฟซซึ่งร่วมกับความหมายของวิธีการทั้งหมดที่มีเหมือนกันและชนิดอื่น ๆ ใช้วิธีการเหล่านี้คือการใช้อินเตอร์เฟซนี้

ตัวอย่าง

/* 定义接口 */
type interface_name interface {
   method_name1 [return_type]
   method_name2 [return_type]
   method_name3 [return_type]
   ...
   method_namen [return_type]
}

/* 定义结构体 */
type struct_name struct {
   /* variables */
}

/* 实现接口方法 */
func (struct_name_variable struct_name) method_name1() [return_type] {
   /* 方法实现 */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
   /* 方法实现*/
}

ตัวอย่าง

package main

import (
    "fmt"
)

type Phone interface {
    call()
}

type NokiaPhone struct {
}

func (nokiaPhone NokiaPhone) call() {
    fmt.Println("I am Nokia, I can call you!")
}

type IPhone struct {
}

func (iPhone IPhone) call() {
    fmt.Println("I am iPhone, I can call you!")
}

func main() {
    var phone Phone

    phone = new(NokiaPhone)
    phone.call()

    phone = new(IPhone)
    phone.call()

}

ในตัวอย่างข้างต้นเรากำหนดโทรศัพท์อินเตอร์เฟซที่อินเตอร์เฟซที่มีวิธีการเรียก () จากนั้นเรากำหนดตัวแปรในการชนิดของฟังก์ชั่นหลักของโทรศัพท์ภายในและผู้ที่ได้รับมอบหมายให้ NokiaPhone และ iPhone แล้วโทรโทร () วิธีการส่งออกผลมีดังนี้

I am Nokia, I can call you!
I am iPhone, I can call you!