문제

This is might not be such a good question, since I don't know of any compiled language that supports this feature, but since Go is constantly surprising me, I'll ask it anyway:

For my own practice, I am writing a little calculator program in Go. I'm wondering if there is a way I can declare and assign a variable of type "Operator", such that I could, for example, write:

var o Operator

o = +

var o1 Operator

o1 = /

and write function like this

func DoOperation(a,b int,o Operator) int{

    return a o b

}

(No, I am not asking about operator overloading.)

Offhand, I don't know of any compiled language that supports such a thing (I'm not an expert in this). I did look at the docs under operators and found nothing. Can Go surprise me again?

Edit: The accepted answer states that Haskell supports this,

도움이 되었습니까?

해결책

No, Go operators are not functions and hence no valid right-hand expressions. They work in a generic way e.g. the plus-operator works on all numeric types and infix-notation a la haskell is not supported either.

You would have to write your own "soft"-generic addition function using reflection.

One compiled language that covers all of your requirements is Haskell.

다른 팁

You can't do exactly what you say, but you can use functions instead. You have to write functions for each operator, but that's relatively little code.

type BinaryOperator func(a, b int) int

func OpAdd(a, b int) int { return a + b }
func OpSub(a, b int) int { return a - b }

func ApplyBinaryOperator(a, b int, op BinaryOperator) int {
    return op(a, b)
}

Coming from an oop background I started doing this :

package main

import "fmt"
type MyInt int64

func (i * MyInt) Add(n MyInt) * MyInt {
    *i += n
    return i
}

func (i MyInt) String() string {
    v := int64(i)
    return fmt.Sprintf("0x%x (%d)", v, v)
}

func main() {
    x := MyInt(10)
    x.Add(10).Add(20).Add(30)
    fmt.Println("x = ", x)
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top