Skip to content

Instantly share code, notes, and snippets.

@func25
Created January 5, 2023 08:29
Show Gist options
  • Save func25/ac3b69c04f4875f2f2d666b65c3d36f1 to your computer and use it in GitHub Desktop.
Save func25/ac3b69c04f4875f2f2d666b65c3d36f1 to your computer and use it in GitHub Desktop.
avoid using interface with only 1 concrete type
package main
import (
"fmt"
"time"
)
type Shape interface {
Area() float64
}
type Circle struct {
radius float64
}
func (c *Circle) Area() float64 {
return 3.14 * c.radius * c.radius
}
func main() {
// Use the Shape interface
start := time.Now()
var s Shape = &Circle{radius: 10}
for i := 0; i < 100000; i++ {
s.Area()
}
elapsed := time.Since(start)
fmt.Printf("Using Shape interface: %s\n", elapsed) // Using Shape interface: 358µs
// Use the Circle type directly
start = time.Now()
c := Circle{radius: 10}
for i := 0; i < 100000; i++ {
c.Area()
}
elapsed = time.Since(start)
fmt.Printf("Using Circle type directly: %s\n", elapsed) // Using Circle type directly: 341.917µs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment