Menu Close

Go – How to access interface fields in go golang

In this tutorial, We are going to learn about how to access interface fields in go golang.

We use interface variable to store any type of value in go golang.

In the given below example, We will learn how to access interface fields in go golang with code.

There are two structures and one interface . One structure is for student’s details and another structure is for teacher’s details. One interface is having get_name method which will return names of student and teacher.

Here, We do not want to access structure’s variable from outside. Hence, To access structure’s variable, we are going to use interface. We can also say it encapsulation in other languages like C++.

Example with code:

package main

import "fmt"

// Declare student structure
type Student struct {
    
    name string
    
}

// Declare teacher structure
type Teacher struct {
    
    name string
    
}

// Declare interface
type Name interface {
    
    get_name() string
    
}

// get_name function for student
func (s Student) get_name() string {
    
    return s.name
    
}

// get_name function for teacher
func (t Teacher) get_name() string {
    
    return t.name
    
}

// Compare student and teacher name. Here, Name is interface type
func name_compare(stud, teacher Name) bool {
    
    if stud.get_name() == teacher.get_name() {
        
        return true
        
    } else {
        
        return false
        
    }
    
}

func main() {
    
    var stud_name, teacher_name string

    // Get the student's name from user
    fmt.Println("Enter student name: ")
    fmt.Scan(&stud_name)

    // Get the teacher's name from user
    fmt.Println("Enter teacher name: ")
    fmt.Scan(&teacher_name)

    // Create structure of student
    student := Student{stud_name}

    // Create structure of teacher
    teacher := Teacher{teacher_name}

    fmt.Print("Is both name are equal: ")
    
    // Call interface function to compare names
    fmt.Print(name_compare(student, teacher))
}

Output:

Enter student name:
John
Enter teacher name:
John
Is both name are equal: true


Enter student name:
john
Enter teacher name:
bob
Is both name are equal: false

Code analysis:

  • get_name method of student returns name of student.
  • get_name method of teacher returns name of teacher.
  • name_compare method is taking function arguments stud and teacher as interface type and returning bool type value.
  • name_compare method is comparing name of student and teacher. if name is equal then it is returning true value else false value.

To learn more about golang, You can refer given below link:

https://www.techieindoor.com/go-lang-tutorial/
https://www.techieindoor.com/go-lang-tutorial/

References:

 https://golang.org/doc/
https://golang.org/pkg/
https://golang.org/pkg/fmt/
https://golang.org/pkg/fmt/#Println
Posted in golang

Leave a Reply

Your email address will not be published. Required fields are marked *