Golang 如何访问接口字段

Golang 如何访问接口字段

Go语言接口与其他语言不同。在Go语言中,接口是一个自定义类型,用于指定一个或多个方法签名的集合,接口是抽象的,因此您不允许创建接口的实例。但是您可以创建一个接口类型的变量,这个变量可以被赋予具有接口所需方法的具体类型值。或者换句话说,接口既是一组方法,也是自定义类型。要了解有关接口的更多信息,请参阅Golang中的文章Interface。

有两个结构和一个接口。一个结构是gfg课程详情,另一个结构是比赛详情。一个接口具有get_name方法,该方法将返回课程和比赛的名称。借助接口,我们将访问结构的变量,因为我们不想从外部访问结构的变量。

示例1: 这个程序将采取2个输入。

// Golang程序访问接口字段
package main
 
import "fmt"
 
//声明课程结构
type Course struct {
    name string
}
 
//声明比赛结构
type Contest struct {
    name string
}
 
//声明接口
type Name interface {
    get_name() string
}
 
//course的get_name函数
func (a Course) get_name() string {
 
    return a.name
 
}
 
//contest的get_name函数
func (b Contest) get_name() string {
 
    return b.name
 
}
 
//比较课程和比赛名称。
//名称是接口类型
func name_compare(course, contest Name) bool {
 
    return contest.get_name() == course.get_name();
 
}
 
func main() {
 
    var course_name, contest_name string
 
    //从用户获取课程名称
    fmt.Println("输入课程名称:")
    fmt.Scan(&course_name)
 
    //从用户获取比赛名称
    fmt.Println("输入比赛名称:")
    fmt.Scan(&contest_name)
 
    //创建课程的结构
    course := Course{course_name}
 
    //创建比赛的结构
    contest := Contest{contest_name}
 
    fmt.Print("课程和比赛是否相同:")
 
    //调用接口函数比较名称
    fmt.Print(name_compare(course, contest))
} 

输出:

输入课程名称: DBMS
输入比赛名称: DBMS
课程和比赛是否相同:true

示例2: 这个程序将采取2个输入。

// Golang 访问接口字段的程序
package main
 
import "fmt"
 
// 声明课程价格结构
type Courseprice struct {
  price int
}
 
// 声明竞赛价格结构
type Couponprice struct {
  price int
}
 
// 声明接口
type Price interface {
  get_price() int
}
 
// Courseprice 的 get_price 函数
func (a Courseprice) get_price() int {
 
  return a.price
}
 
// Couponprice 的 get_price 函数
func (b Couponprice) get_price() int {
 
  return b.price
}
 
// 比较 courseprice 和 Couponprice
// Price 是接口类型
func price_compare(courseprice, Couponprice Price) bool {
 
  if courseprice.get_price() <= Couponprice.get_price() {
 
    return true
 
  } else {
 
    return false
 
  }
}
 
func main() {
 
  var courseprice, Couponprice int
 
  // 获取用户输入的 courseprice
  fmt.Println("输入课程价格:")
  fmt.Scan(&courseprice)
 
  // 获取用户输入的 Couponprice
  fmt.Println("输入优惠券价格:")
  fmt.Scan(&Couponprice)
 
  // 创建 Courseprice 结构
  course := Courseprice{courseprice}
 
  // 创建 Couponprice 结构
  Coupon := Couponprice{Couponprice}
 
  fmt.Print("是否免费:")
 
  // 调用接口函数比较价格
  fmt.Print(price_compare(course, Coupon))
} 

输出:

输入课程价格:1000
输入优惠券价格:700
是否免费:false

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程