How to Access Interface Fields in Golang?
Go language interfaces are different from other languages. In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface. But you are allowed to create a variable of an interface type and this variable can be assigned with a concrete type value that has the methods the interface requires. Or in other words, the interface is a collection of methods as well as it is a custom type. To read more about Interfaces, please refer to the article Interface in Golang
There are two structures and one interface. One structure is for gfg course details and another structure is for contest details. One interface is having get_name method which will return names of course and contest. With the help of the interface, we will access the structure’s variable as we don’t want to access the structure’s variable from outside.
Example 1: This program will take 2 inputs.
Go
package main
import "fmt"
type Course struct {
name string
}
type Contest struct {
name string
}
type Name interface {
get_name() string
}
func (a Course) get_name() string {
return a.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( "Enter course name: " )
fmt.Scan(&course_name)
fmt.Println( "Enter contest name: " )
fmt.Scan(&contest_name)
course := Course{course_name}
contest := Contest{contest_name}
fmt.Print( "Is same subjects in course and contest: " )
fmt.Print(name_compare(course, contest))
}
|
Output:
Enter course name: DBMS
Enter contest name: DBMS
Is same subjects in course and contest: true
Example 2: This program will take 2 inputs.
Go
package main
import "fmt"
type Courseprice struct {
price int
}
type Couponprice struct {
price int
}
type Price interface {
get_price() int
}
func (a Courseprice) get_price() int {
return a.price
}
func (b Couponprice) get_price() int {
return b.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
fmt.Println( "Enter course price: " )
fmt.Scan(&courseprice)
fmt.Println( "Enter Coupon Price: " )
fmt.Scan(&Couponprice)
course := Courseprice{courseprice}
Coupon := Couponprice{Couponprice}
fmt.Print( "Is the course is free: " )
fmt.Print(price_compare(course, Coupon))
}
|
Output:
Enter course price: 1000
Enter Coupon Price: 700
Is the course is free: false
Last Updated :
31 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...