使用 operator import 包含模块

Including modules using operator import

我看了“打包教程”一节,说实话,没看懂多少。但我很清楚我想要得到什么。

  1. 我有两个文件,bs_func.toit,其中包含 binary_search 函数,以及bs_test.toit,它使用了这个函数:

bs_func.toit

binary_search list needle:
  from := 0
  to := list.size - 1
  while from <= to :
    mid := (to + from) / 2
    if list[mid] == needle :
      return mid
    else if list[mid] < needle :
      from = mid + 1
    else if list[mid] > needle :
      to = mid - 1
  return -1

bs_test.toit

import ???
main:
  list := List 16: it * 2
  print "Binary Search"
  print "List: $list"
  number := 8
  index := binary_search list number
  print "index of $number is $index"
  1. 我只需要通过 导入将 binary_search 包含在 bs_test.toit声明。
  2. package.lock 文件的实验以失败告终,所以我只想获得有关如何在我的案例中执行此操作的说明。
  3. 我正在使用 VCS。

提前致谢,MK

既然你参考了包教程,我假设你有以下布局:

  • 一个包文件夹。假设 bs,但名称不相关,
  • bssrc 文件夹中的文件 bs_func.toit。所以bs/src/bs_func.toit
  • bs_test.toitbstest 文件夹中。所以 bs/tests/bs_test.toit.

bs_test.toit 导入 bs_func.toit 的最简单方法是打点,然后进入 src 文件夹:

import ..src.bs_func // double dot goes from bs/src to bs/, and .src goes into bs/src.

为了保证只有`binary_search是可见的,可以这样限制导入:

import ..src.bs_func show binary_search

一种不同的(并且可能是首选的)方法是导入 bs_func.toit 就好像它是一个包的一部分(无论如何它应该成为)。 (注意:我将更改教程以遵循该方法)。

你想从给测试目录一个 package.lock 文件开始,表明 imports 应该使用它来找到他们的目标。

# Inside the bs/tests folder:
toit pkg init --app

这应该创建一个 package.lock 文件。

我们现在可以使用 --local 标志导入包:

# Again in the tests folder
toit pkg install --local --prefix=bs ..

这表示:将本地 (--local) 文件夹“..”(..) 安装为前缀为“bs”的包 (--prefix=bs)。

现在我们可以使用这个前缀来导入包(因此 bs_func.toit):

import bs.bs_func

main:
  ...
  index := bs.binary_search list number
  ...

如您所见:只需导入带有 bs.bs_func 的文件即可为其提供前缀 bs。您可以使用 show:

来避免前缀
import bs.bs_func show binary_search

main:
  ...
  index := binary_search list number
  ...