Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
package main
import "fmt"
type Shape interface{ Area() float64 }
type Square struct{ Side int }
func (s Square) Area() int { return s.Side * s.Side }
func main() {
var sh Shape = Square{Side: 2}
fmt.Println(sh.Area())
}It does not compile
- Expecting
4: a type implements an interface only when each method has the same parameters and results, and thisAreareturnsint, notfloat64. - Expecting a panic at run time: the compiler checks the methods when
Square{Side: 2}is assigned to aShapevariable, so the program never runs.
- How would you change
Squareso that the program compiles and prints4? - Why does Go check interface satisfaction at compile time rather than at the call?