有没有一种方法可以使私人具有公共特征? [英] Is there a way to have private functions in public traits?

查看:80
本文介绍了有没有一种方法可以使私人具有公共特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个针对公共特征的实现,该实现在多个函数上重复了一些工作,因此我想用一个完成共享工作的函数将其干燥,并从实际上要使用的函数中调用它.所以我有:

I have an implementation for a public trait that repeats some work over multiple functions, so I'd like to DRY it up with a function that does the shared work, to be called from the functions actually meant to be used. So I have:

  • fn do_private_thing()
  • fn do_pub_1()
  • fn do_pub_2()
  • fn do_private_thing()
  • fn do_pub_1()
  • fn do_pub_2()

我不希望do_private_thing()在文档中公开或直接使用,因为从特性/实现的用户角度来看,它并没有做任何有用的事情.但是具有公共特征的功能不是私有的.

I don't want do_private_thing() to be exposed in docs or used directly, because it doesn't do anything useful from the perspective of a user of the trait/implementation. But functions in public traits are not private.

我可以在trait实现所在的模块中将do_private_thing设为私有函数,但是trait确实要求该函数的工作可以通过trait的任何实现来完成.因此,如果我将该代码留在实现中,我会觉得有点撒谎.

I could make do_private_thing a private function in the module where the trait implementation is located, but the trait does require that that function's work be done by any implementation of the trait. So I feel like I'm lying a little bit if I leave that code out of the implementation.

在Rust中进行合理布局的合理方法是什么?

What's the reasonable way to lay this out in Rust?

推荐答案

我可以在trait实现所在的模块中将do_private_thing设为私有函数

这就是我要做的.

,但是特征确实要求该功能的工作必须由特征的任何实现来完成.因此,如果我将该代码留在实现中,我会觉得有点撒谎.

but the trait does require that that function's work be done by any implementation of the trait. So I feel like I'm lying a little bit if I leave that code out of the implementation.

这开始变得不太清楚了.当您说该特征的任何实现时,我就不再理解为什么要将其设为私有.如果该特性的另一个实现者需要此代码,则应以某种方式将其公开.

This starts to be a bit less clear. When you say any implementation of the trait, then I no longer understand why you'd want to make it private. If another implementer of the trait needs this code, then it should be public in some fashion.

在许多方面,这与如何测试私有方法"这个问题非常相似.我的正常答案是:不要.而是,将要测试的代码提取到新的公共项目中,然后单独测试该项目.通常的问题是人们不想在特定状态下公开功能 ,而不是他们根本不想公开功能.

In many ways, this feels very similar to the question "how do I test private methods". My normal answer there is: don't. Instead, extract the code you want to test to a new public item and then test the item in isolation. The usual problem is that people don't want to expose the functionality on a specific piece of state, not that they don't want to expose the functionality at all.

在这种情况下,创建一个包含共享逻辑的新类型,然后可以由需要它的任何人公开和使用.或者,创建一个可以通过实现您的特征的类型进行参数化的类型,并提供所需的任何其他功能.

In this case, create a new type that incorporates the shared logic and can then be exposed and used by whoever needs it. Alternatively, create a type that can be parameterized by a type implementing your trait and provides whatever extra functionality you need.

这篇关于有没有一种方法可以使私人具有公共特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆