英文:
Is it possible to extend go struct constructors?
问题
给定
type Rectangle struct {
    h, w int
}
func (rec *Rectangle) area() int {
    return rec.w * rec.h
}
你能使用Rectangle定义一个Square结构体,以便我可以使用area方法吗?如果不可能的话,完全没关系。我不会评判这门语言,也不会哭或生气。我只是在学习Go语言。
英文:
given
type Rectangle struct {
    h, w int
}
func (rec *Rectangle) area() int {
    return rec.w * rec.h
}
Can you define a Square struct using Rectangle, so I can make use of area method? It is absolutely fine if it is not possible. I won't judge the language or cry or get upset. I am just learning the golang.
答案1
得分: 5
Go不是经典的面向对象语言,因此它没有继承。它也没有构造函数。它所具有的是嵌入。因此,下面的代码是可能的:
type Rectangle struct {
    h, w int
}
func (rec *Rectangle) area() int {
    return rec.w * rec.h
}
type Square struct {
    Rectangle
}
这里的主要限制是area()方法无法访问仅存在于Square中的字段。
英文:
Go isn't classically object-oriented, so it doesn't have inheritence. It also doesn't have constructors. What it does have is embedding. Thus this is possible:
type Rectangle struct {
    h, w int
}
func (rec *Rectangle) area() int {
    return rec.w * rec.h
}
type Square struct {
    Rectangle
}
The main limitation here is that there's no way for the area() method to access fields that only exist in Square.
答案2
得分: 1
我了解到实现这种行为的预期方法是编写普通函数。请参考MakeSquare。
type Rectangle struct {
    h, w int
}
func (rec *Rectangle) area() int {
    return rec.w * rec.h
}
type Square struct {
    Rectangle
}
func MakeSquare(x int) (sq Square) {
    sq.h = x
    sq.w = x
    return
}
func Test_square(t *testing.T) {
    sq := MakeSquare(3)
    assert.Equal(t, 9, sq.area())
}
这段代码定义了一个矩形(Rectangle)结构体和一个正方形(Square)结构体。Square结构体嵌入了Rectangle结构体,从而继承了Rectangle的属性和方法。MakeSquare函数用于创建一个边长为x的正方形,并返回该正方形。Test_square函数用于测试正方形的面积是否正确。
英文:
I came to know that the expected way to achieve this behaviour is to write ordinary functions. see MakeSquare
type Rectangle struct {
	h, w int
}
func (rec *Rectangle) area() int {
	return rec.w * rec.h
}
type Square struct {
	Rectangle
}
func MakeSquare(x int) (sq Square) {
	sq.h = x
	sq.w = x
	return
}
func Test_square(t *testing.T) {
	sq := MakeSquare(3)
	assert.Equal(t, 9, sq.area())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论