如何为golang中的变量分配运算符?

如何为golang中的变量分配运算符?,go,Go,是否可以将中缀运算符指定给变量 operator := << operator:=您可以将运算符包装到函数()中: 主程序包 进口( “fmt” ) func main(){ 运算符:=[]func(int)int{left,left,left,right,right} 值:=4 对于u,运算符:=范围运算符{ 值=运算符(值) 格式打印项次(值) } } func左(x int)int{ 返回x>1 } 这张照片是: 8 16 32 16 八, 可以将运算符包装到函数()中:

是否可以将中缀运算符指定给变量

operator := <<

operator:=您可以将运算符包装到函数()中:

主程序包
进口(
“fmt”
)
func main(){
运算符:=[]func(int)int{left,left,left,right,right}
值:=4
对于u,运算符:=范围运算符{
值=运算符(值)
格式打印项次(值)
}
}
func左(x int)int{
返回x>1
}
这张照片是:

8
16
32
16
八,


可以将运算符包装到函数()中:

主程序包
进口(
“fmt”
)
func main(){
运算符:=[]func(int)int{left,left,left,right,right}
值:=4
对于u,运算符:=范围运算符{
值=运算符(值)
格式打印项次(值)
}
}
func左(x int)int{
返回x>1
}
这张照片是:

8
16
32
16
八,


不,不可能在变量中存储运算符

也许最好的方法是定义一组操作,并使用
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
  }
}

不,不可能在变量中存储运算符

也许最好的方法是定义一组操作,并使用
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