gRPC的Go语言常量的proto是什么?

huangapple go评论66阅读模式
英文:

What is the grpc proto for golang const?

问题

如果我有以下的golang代码:

type Animal string
const (
  Cat   Animal = "cat"
  Dog   Animal = "dog"
  Mouse Animal = "mouse"
)

我应该如何编写proto文件?如果我使用枚举,那么我是否需要手动进行映射?

enum Animal {
  CAT = 0;
  DOG = 1; 
  MOUSE = 2;
}
英文:

If I have the golang

type Animal string
const (
  Cat   Animal = "cat"
  Dog   Animal = "dog"
  Mouse Animal = "mouse"
)

How should I write the proto? If I use enums I will then need to manually map across myself?

enum Animal {
  CAT = 0;
  DOG = 1; 
  MOUSE = 2;
}

答案1

得分: 2

你可以动态访问,像这样:

import (
	"fmt"
	pb "animal"
)

func main() {
	type Animal string
	const (
		Cat   Animal = "CAT"
		Dog   Animal = "DOG"
		Mouse Animal = "MOUSE"
	)
	
	myProtoAnimal := pb.Animal(pb.Animal_value[string(Cat)])

	fmt.Printf("%T=%v", myProtoAnimal, myProtoAnimal)

}

将打印出:

animal.Animal=CAT
英文:

You could access dynamically like:

import (
	"fmt"
	pb "animal"
)
func main() {
	type Animal string
	const (
		Cat   Animal = "CAT"
		Dog   Animal = "DOG"
		Mouse Animal = "MOUSE"
	)
	
	myProtoAnimal := pb.Animal(pb.Animal_value[string(Cat)])

	fmt.Printf("%T=%v", myProtoAnimal, myProtoAnimal)

}

Will print

animal.Animal=CAT



</details>



huangapple
  • 本文由 发表于 2022年1月5日 19:39:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/70592223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定