On 2013-11-29 09:29, Bienlein wrote:
On Thursday, 28 November 2013 at 19:22:06 UTC, Andrei Alexandrescu wrote:
Interesting. Could you please create a paste with the two code samples?
Thanks,
Andrei
Hello,
here is the Go code:
package main
import (
"fmt"
)
type Point struct {
x, y int
}
type Rectangular struct {
topLeft, bottomRight Point
}
func (self Rectangular) Left() int {
return self.topLeft.x
}
func (self Rectangular) Right() int {
return self.bottomRight.x
}
func (self Rectangular) Width() int {
return self.Right() - self.Left()
}
type Rectangle struct {
Rectangular
}
func NewRectangle(topLeft, bottomRight Point) *Rectangle {
rectangle := new(Rectangle)
rectangle.Rectangular.topLeft = topLeft
rectangle.Rectangular.bottomRight = bottomRight
return rectangle
}
func main() {
rectangle := NewRectangle(Point{1, 2}, Point{12, 2})
fmt.Println(rectangle.Width())
}
And this is the Scala code:
import java.awt.Point
trait Rectangular {
protected val topLeft: Point
protected val bottomRight: Point
def width : Int = bottomRight.x - topLeft.x
}
class Rectangle(val topLeft: Point, val bottomRight: Point) extends
Rectangular
object RunIt extends Application {
val rectangle = new Rectangle(new Point(1, 2), new Point(12, 2))
println(rectangle.width)
}
I guess in D you would do something like this:
mixin template Rectangular() {
Point x, y;
}
mixin Rectangular;
struct Rectangle {
mixin Rectangular;
}
Note that in the Scala code Rectangular.topLeft and
Rectangular.bottomRight are protected. Since the solution in Go makes
use of delegation this can only be accomplished in Go through making
getters public or defining Rectangle in the same package as Rectangular.
Since Go does not have constructors the way to initialize a Rectangle in
Go looks more clumsy.
An interesting point to me is that Rectangular in Go is just an ordinary
struct whereas Rectangular is a special construct in Scala (being a
trait) and in D (being a mixin). So Scala and D force you to design
ahead, e.g. you have to decide in advance whether to make Rectangular a
trait or mixin. Thereafter, Rectangular is not of use on its own, only
when used as a trait or mixin.
What makes me think is whether delegation as a language construct has
been underrated and whether Go now makes this obvious.
You can do the exact thing in D with the help of UFCS. BTW, you need to
decide in advance if you should use a class or a struct in D. That's
basically the same thing as choosing if you need a template.
--
/Jacob Carlborg