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

问题描述

我已经阅读了“打包教程”部分,坦率地说,我并没有太多了解。但我确切地知道我想要什么。

  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. package.lock 文件的实验以失败告终,所以我只想获得有关如何在我的情况下执行此操作的说明。
  3. 我正在使用 VCS。

提前致谢,MK

解决方法

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

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

bs_func.toit 导入 bs_test.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”(--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
  ...