包括使用运算符导入的模块



我已经阅读了;包教程";老实说,我不太明白。但我很清楚我想要得到什么。

  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. 我只需要通过import语句将binary_search包含在bs_test.toit
  2. 使用包.lock文件的实验以失败告终,所以我只想了解如何在我的情况下做到这一点
  3. 我正在使用VCS

提前感谢,MK

由于您参考了软件包教程,我假设您有以下布局:

  • 一个包文件夹。假设bs,但名称并不相关
  • 在CCD_ 4的CCD_ 3文件夹内的文件CCD_。因此bs/src/bs_func.toit,以及
  • bstest文件夹中的bs_test.toit。所以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文件,指示import应该使用它来查找目标。

# 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";(bs_func.toit0(。

现在我们可以使用这个前缀来导入包(从而导入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
...

最新更新