data []int
sort.Sort(sort.Interface {
Len: func() int {
return len(data)
},Less: func(i, j int) bool {
return data[i] < data[j]
},Swap: func(i, j int) {
data[i], data[j] = data[j], data[i]
},
})
On 08/07/2013 1:11 PM, "David DENG" <david...@gmail.com> wrote:
> One powerful point of this compared to defining a new type implementing the interface is that you can use closures.
>
> How you guys think of this?
What happens when I do a type assertion on this? Or pass it to reflect?
What value and concrete type is it in a comparison or a type switch?
If I convert it to another interface, can I convert it back?
e.g.:http://play.golang.org/p/1Z0uXVzdG3The compiler won't fail for every typo mistakes.
--
func main() {data := []Foo{};type Indexes []intfunc (idx Indexes) Less(i, j int) bool {return data[idx[i]].Score < data[idx[j]].Score}}
The grammar looks like this:data []intsort.Sort(sort.Interface {
Len: func() int {return len(data)},Less: func(i, j int) bool {
return data[i] < data[j]
},Swap: func(i, j int) {
data[i], data[j] = data[j], data[i]},})
var an intb := int(2)c := 3var d = int(4)var e = 5var f int = 6
v := forge(Len, func() int { ... },Less, func(i, j int) bool {...},Swap, func(i, j, int) { ... });sort.Sort(v.(sort.Interface))
Sorry, Len/Less/Swap should be strings: "Len", "Less", "Swap".Besides RPC, json/gob's marshal/unmarshaling can be done much more efficient for unified data, since reflection is only used in intialization stage.
--
// shared
type Adder interface {Add(a, b int) int}// servertype RealAdder struct {}func (a RealAdder) Add(a, b int) int {return a + b}server := RpcServer(&RealAdder{})// client
client := RpcClient(remoteAddr).(Adder)
c := client.Add(a, b)
RPC (I mean "net/rpc") can be designed in this way:// sharedtype Adder interface {Add(a, b int) int}// servertype RealAdder struct {}func (a RealAdder) Add(a, b int) int {return a + b}server := RpcServer(&RealAdder{})// clientclient := RpcClient(remoteAddr).(Adder)c := client.Add(a, b)
You can require the last return value must be an error, for reporting of network failure.
David
On Thursday, July 11, 2013 9:01:02 AM UTC+8, Jesse McNelis wrote:On Thu, Jul 11, 2013 at 10:50 AM, David DENG <david...@gmail.com> wrote:--RPC (I mean "net/rpc") can be designed in this way:// sharedtype Adder interface {Add(a, b int) int}// servertype RealAdder struct {}func (a RealAdder) Add(a, b int) int {return a + b}server := RpcServer(&RealAdder{})// clientclient := RpcClient(remoteAddr).(Adder)c := client.Add(a, b)There is a really good reason why RPC doesn't work like this.Networks are never transparent.
=====================
http://jessta.id.au
Zero values for normal values, and the network error at the last.
--