首页 \ 问答 \ map [Task] int64其中Task是一个接口(map[Task]int64 where Task is an interface)

map [Task] int64其中Task是一个接口(map[Task]int64 where Task is an interface)

假设我在Go库中定义了以下接口:

type Task interface {
    Do() error
}

func Register(task Task) { ... }

func GetId(task Task) int64 { ... }

Register() ,库将唯一的int64与每个任务实例相关联。 GetId()必须返回给定任务的标识符。

我最初的想法是将关联存储为map[Task]int64 。 这似乎工作正常,但有人告诉我,如果实现Task的对象不具有可比性(例如,包含mapstruct ),它将会中断。 我仍然需要检查这是否属实。

我打算尝试使用一块struct { task Task; id int64 } struct { task Task; id int64 }而不是迭代它,但这仍然需要与可比较的Task实例相等。 和AFAIU在Go中没有身份比较。

如何从Task实例到其ID具有强大的映射?

编辑:到目前为止提出的两个解决方案都有效,但它们的缺点是每个Task实现都必须包含一些重复的代码来处理ID。 我可以在可以嵌入的TaskBase struct中提供该代码,但理想情况下,我更喜欢一种不需要实现甚至知道ID的解决方案(它们是库内部的,并且在它之外没有任何意义)。


Let's say I define the following interface in a Go library:

type Task interface {
    Do() error
}

func Register(task Task) { ... }

func GetId(task Task) int64 { ... }

In Register(), the library associates a unique int64 with each task instance. GetId() must return the identifier for the given task.

My initial idea was to store the association as a map[Task]int64. This seems to work fine, but I was told that it would break if an object implementing Task was not equality-comparable (for example, a struct containing a map). I still need to check if this is true.

I was going to try and use a slice of struct { task Task; id int64 } instead and just iterate over it, but that would still require equality comparable Task instances. And AFAIU there is no identity comparison in Go.

How can I have a robust mapping from Task instances to their ID?

EDIT: Both solutions proposed so far work, but they have the disadvantage that every Task implementation has to include some repetitive code to handle the IDs. I could provide that code in a TaskBase struct that could be embedded, but ideally I would prefer a solution that doesn't require implementations to even know about the IDs (they are internal to the library and have no meaning outside of it).


原文:https://stackoverflow.com/questions/13519152
更新时间:2022-04-25 21:04

最满意答案

您可以生成函数的number副本,每个副本都有独立的 lru_cache包装器:

setup = '''\
    from {name} import recursive_function as f
    f = iter([
        functools.lru_cache(maxsize=None)(recursive_function.__wrapped__)
        for _ in range({number})])
    n = {n}
    next_ = next
'''.format(name=__name__, number=number, n=n)
test = '''\
    recursive_function = next_(f)
    recursive_funcion.__globals__['recursive_funcion'] = recursive_funcion
    recursive_function(n)
'''
return timeit.timeit(test, setup, number=number)

该设置预先创建number独立装饰的功能对象,每个功能对象都有一个不同的LRU缓存,并为此创建一个迭代器。 然后,测试使用next()函数获取下一个可用的函数对象,并将其用于测试。

但是,每次都必须替换当前的全局名称recursive_function ,否则递归调用将找不到新的装饰版本。 这有点不利,不要运行计时器并且期望​​缓存在之后是空的(它将包含最后一次测试运行的结果)。

这是因为:

  1. 原始的非缓存函数仍可用作recursive_function.__wrapped__
  2. decorator语法只是用于调用decorator对象以生成新函数对象的语法糖。

这为每个单独的测试提供了一个干净的缓存,只需要很少的开销(只有一个next()调用,它已被绑定到本地以避免全局名称查找惩罚)。


You could produce number copies of the function, each with their independent lru_cache wrapper:

setup = '''\
    from {name} import recursive_function as f
    f = iter([
        functools.lru_cache(maxsize=None)(recursive_function.__wrapped__)
        for _ in range({number})])
    n = {n}
    next_ = next
'''.format(name=__name__, number=number, n=n)
test = '''\
    recursive_function = next_(f)
    recursive_funcion.__globals__['recursive_funcion'] = recursive_funcion
    recursive_function(n)
'''
return timeit.timeit(test, setup, number=number)

The setup creates number individually decorated function objects up front, each with a distinct LRU cache, and creates an iterator for this. The test then uses the next() function to obtain the next available function object, and uses that for the test.

You do have to replace the current global name recursive_function each time however, as otherwise the recursive call won't find the new decorated version. This is a bit of a downside, don't run the time trial and expect the cache to be empty afterwards (it'll contain the results of the very last test run instead).

This works because:

  1. the original un-cached function is still available as recursive_function.__wrapped__
  2. decorator syntax is just syntactic sugar for a call to the decorator object to produce a new function object.

This gives each individual test a clean cache, with minimal overhead (only a next() call, which has been bound to a local to avoid the global name lookup penalty).

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)