如何在golang中为一个变量赋一个操作符?

时间:2017-10-22 07:29:15

标签: go

是否可以将中缀运算符分配给变量?

operator := <<

如果是这样,它如何应用于参数?

2 个答案:

答案 0 :(得分:2)

不,不可能将操作符存储在变量中。

也许最好的方法是定义一组操作并使用Apply方法创建一个包装结构:

type Operation int

const (
  Left Operation = iota
  Right
)

type State struct {
  Value int
}

func (s *State) Apply(o Operation) {
  switch (o) {
    case Left:
       s.Value = s.value << 1
    case Right:
       s.Value = s.value >> 1
  }
}

样品使用:

value := State{4} // original value
op := Left
value.Apply(op) // s.Value is now 8

答案 1 :(得分:1)

您可以将操作符包装在函数(playground)中:

package main

import (
    "fmt"
)

func main() {
    operators := []func(int)int{left, left, left, right, right}

    value := 4

    for _, operator := range operators {
        value = operator(value)
        fmt.Println(value)
    }
}

func left(x int) int {
    return x << 1
}

func right(x int) int {
    return x >> 1
}

打印:

  

8
  16个
  32个
  16个
  8