相关疑难解决方法(0)

我可以在Go中使用反射创建一个新函数吗?

我有一个想法,在Go中使用接口来定义RPC样式接口.所以对于给定的服务,我可能会创建一个这样的接口:

type MyService interface{
  Login(username, password string) (sessionId int, err error)
  HelloWorld(sessionId int) (hi string, err error)
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是使用反射来实现该接口,将方法调用转换为RPC调用,对输入参数进行封送,并将结果解组回到方法的输出中.我知道如果我能得到输入参数的[]接口{},我可以使用反射来进行服务调用.但是,我没有看到任何方法使用反射动态创建一个值,通过调用我的反射使用函数来实现接口.有没有人知道这样做的方法,即使使用不安全?

reflection go

11
推荐指数
2
解决办法
2284
查看次数

是否可以在Go中动态创建带有接收器(方法)的函数?

我正在阅读有关reflect.MakeFunc的内容,并且想知道是否还有一种方法可以在运行时创建方法带有接收器的函数)。

reflection methods runtime go

5
推荐指数
1
解决办法
2358
查看次数

在go lang中按不同的维度对点(结构)进行排序

我有一个Points类型的多维点列表.

我已经实现了sort.Sort界面,现在可以排序了y value.

例如

type Points []*Point

func (points Points) Len() int {
    return len(points)
}
func (points Points) Less(i, j int) bool {
    return points[i].y < points[j].y
}
func (points Points) Swap(i, j int) {
    points[i], points[j] = points[j], points[i]
}

type Point struct {
    x int
    y int
    country_id int
}
Run Code Online (Sandbox Code Playgroud)

现在我想用x value而不是来分类我的观点y value.

我的想法是使用带有全局标志的if语句(可以在排序之前打开或关闭):

func (points Points) Less(i, j int) bool {
    if SORT_BY_X {
        return points[i].x < points[j].x …
Run Code Online (Sandbox Code Playgroud)

sorting struct go

4
推荐指数
2
解决办法
1869
查看次数

在 Go 中通过反射创建结构

我想完全动态地定义一个结构体,这样我就可以得到下面的结构体,但不先定义它?

type Data struct {
   a string
   b int `json:"b"`
}
d := Data{}
Run Code Online (Sandbox Code Playgroud)

go

0
推荐指数
1
解决办法
549
查看次数

标签 统计

go ×4

reflection ×2

methods ×1

runtime ×1

sorting ×1

struct ×1