Related Articles

Related Articles

Function that takes an interface type as value and pointer in Golang
  • Last Updated : 17 May, 2020

Functions are generally the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, provides better readability of the code. So basically, a function is a collection of statements that perform some specific task and return the result to the caller. A function can also perform some specific task without returning anything.

Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.).

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.

Now you can create a function that takes interface type as a value and pointer. To understand this concept see the below example:





// Golang Function that takes an interface
// type as value and pointer
package main
import "fmt"
// taking an interface
type CoursePrice interface {
// taking a function that accept
// CoursePrice interface as an value
func show(cp CoursePrice, fee int) {
// taking a struct
type Dsa struct {
    Price int
func (c Dsa) show(fee int) {
    c.Price = fee
// taking a struct
type Placement struct {
    Price int
// function accepting a pointer
func (p *Placement) show(fee int) {
    p.Price = fee
// main function
func main() {
    first := Dsa{Price: 2499}
    second := Placement{Price: 9999}
    // calling the function
    show(first, 1999)
    // calling the function
    // by passing the address
    show(&second, 7999)
    fmt.Println("DSA Course Fee:", first.Price)
    fmt.Println("Placement100 Course Fee:", second.Price)



DSA Course Fee: 2499
Placement100 Course Fee: 7999

My Personal Notes arrow_drop_up
Recommended Articles
Page :