Created
June 26, 2020 07:14
-
-
Save sriharshaj/20f82cede51e8a4f6e233abdbb4d9b53 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
type Square struct { | |
side float32 | |
} | |
type Circle struct { | |
radius float32 | |
} | |
type Shaper interface { | |
Area() float32 | |
Circum() float32 | |
} | |
func main() { | |
var areaIntf Shaper | |
sq1 := Square{5} // Try using val | |
// sq1.side = 5 | |
areaIntf = sq1 | |
// Is Square the type of areaIntf ? | |
if t, ok := areaIntf.(*Square); ok { | |
fmt.Printf("The type of areaIntf is: %T\n", t) | |
} | |
if u, ok := areaIntf.(*Circle); ok { | |
fmt.Printf("The type of areaIntf is: %T\n", u) | |
} else { | |
fmt.Println("areaIntf does not contain a variable of type Circle") | |
} | |
} | |
func (sq *Square) Area() float32 { | |
return sq.side * sq.side | |
} | |
func (sq *Square) Circum() float32 { | |
return 4 *sq.side | |
} | |
func (ci Circle) Area() float32 { | |
return ci.radius * ci.radius * math.Pi | |
} | |
func (ci Circle) Circum() float32 { | |
return 2 * ci.radius * math.Pi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When you call a method on an interface, it must either have an identical receiver type or it must be directly discernible from the concrete type:
Pointer methods can be called with pointers.
Value methods can be called with values.
Value-receiver methods can be called with pointer values because they can be dereferenced first.
Pointer-receiver methods cannot be called with values; however, because the value stored inside an interface has no address.