这是从文件中读取行并将它们分解成Rust中的单词的正确方法吗?(Is this the right way to read lines from file and split them into words in Rust?)

编者按:本代码示例来自1.0之前的Rust版本,并且不具有语法上有效的Rust 1.0代码。 此代码的更新版本会产生不同的错误,但答案仍然包含有价值的信息。

我已经实现了下面的方法来从2维数据结构中的文件中返回单词:

fn read_terms() -> Vec<Vec<String>> {
    let path = Path::new("terms.txt");
    let mut file = BufferedReader::new(File::open(&path));
    return file.lines().map(|x| x.unwrap().as_slice().words().map(|x| x.to_string()).collect()).collect();
}

这是否是Rust中正确,习惯和有效的方式? 我想知道collect()需要经常调用,以及是否需要在这里调用to_string()来分配内存。 也许返回类型应该被定义为不同的地方,以更加地道和有效?


Editor's note: This code example is from a version of Rust prior to 1.0 and is not syntactically valid Rust 1.0 code. Updated versions of this code produce different errors, but the answers still contain valuable information.

I've implemented the following method to return me the words from a file in a 2 dimensional data structure:

fn read_terms() -> Vec<Vec<String>> {
    let path = Path::new("terms.txt");
    let mut file = BufferedReader::new(File::open(&path));
    return file.lines().map(|x| x.unwrap().as_slice().words().map(|x| x.to_string()).collect()).collect();
}

Is this the right, idiomatic and efficient way in Rust? I'm wondering if collect() needs to be called so often and whether it's necessary to call to_string() here to allocate memory. Maybe the return type should be defined differently to be more idiomatic and efficient?


原文:https://stackoverflow.com/questions/25581463
2024-04-22 10:04

满意答案

找出问题所在,我将分享我的见解:

addJavascriptInterface函数仅在调用BEFORE loadUrl / loadData函数时才适用。

在我的情况下 - 我期望addJavascriptInterface注入一个JS桥,但我从来没有重新加载WebView内容,因此从未主动注入。

重新加载WebView HTML内容后,桥接器按预期添加。


Figured out the problem, so I'll share my insights:

The addJavascriptInterface function applies only if called BEFORE a loadUrl / loadData function.

In my case - I expected addJavascriptInterface to inject a JS bridge, but I never reloaded the WebView content, so it was never actively injected.

After reloading the WebView HTML content, the bridge was added as expected.

相关问答

更多

可抽取的api <21(Drawable tinting for api <21)

使用AppCompatImageView像这样: <android.support.v7.widget.AppCompatImageView android:id="@+id/my_appcompat_imageview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/my_image" ...

addJavascriptInterface函数在API 21上不起作用(addJavascriptInterface function doesn't work on API 21)

找出问题所在,我将分享我的见解: addJavascriptInterface函数仅在调用BEFORE loadUrl / loadData函数时才适用。 在我的情况下 - 我期望addJavascriptInterface注入一个JS桥,但我从来没有重新加载WebView内容,因此从未主动注入。 重新加载WebView HTML内容后,桥接器按预期添加。 Figured out the problem, so I'll share my insights: The addJavascriptIn...

LibGDX无法在Android API 21上运行?(LibGDX not work on Android API 21?)

由于几天后我处于类似情况,我认为以下内容可能有效(假设您在项目中使用BaseGameUtils,或者使用appCompat的任何模块) 在Android Studio中打开项目 双击使用appCompat的模块的build.gradle文件(对我来说,它是BaseGameUtils) 更改依赖关系如下(抱歉格式错误,我赶时间): 依赖{compile'com.android.support:appcompat-v7:22.0.0'compile'com.android.support:suppor...

比较API 21 x API 23中的资源(Comparing resources in API 21 x API 23)

您可以尝试使用ContextCompat: ContextCompat.getDrawable(yourContext, R.drawable.myDrawable).getConstantState(); You can try using ContextCompat: ContextCompat.getDrawable(yourContext, R.drawable.myDrawable).getConstantState();

Snackbar API 21(Snackbar with API 21)

您应该尝试使用Android Studio,因为Eclipse的ADT插件不再处于积极的开发阶段。 在Android Studio中,您只需在build.gradle依赖项中添加一行compile 'com.nispok:snackbar:2.6.1' ,例如 dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0....

API 21中的CollapsingToolbarLayout(CollapsingToolbarLayout in API 21)

由于v21主题更改为包括: <item name="android:windowDrawsSystemBarBackgrounds">true</item> 需要在v21的工具栏上修改边距,以考虑系统栏占用的空间。 dimens.xml <dimen name="action_bar_margin_top">0dp</dimen> dimens.xml(v21) <dimen name="action_bar_margin_top">-24dp</dimen> 将margin和fitsSys...

API 21下的主要暗色android(primary dark color android under API 21)

您可以针对不同的API级别使用不同的样式。 对于API <21,您将使用正常的res/values/styles.xml ,然后对于API 21+,您将拥有res/values-v21/styles.xml 。 如果设备运行API 21或更高版本,则它将使用-v21文件夹中的文件。 如果您只想设置<color>值,那么只需将这些键命名为相同,然后对colors.xml执行相同的colors.xml 。 http://developer.android.com/guide/topics/resour...

CUDA线程块大小1024不起作用(cc = 20,sm = 21)(CUDA thread block size 1024 doesn't work (cc=20, sm=21))

我用当前信息填写了CUDA占用计算器文件: 计算能力:2.1 每块线程:961 每个线程的注册:34 共享内存:0 我的入住率为0% ,受寄存器数限制。 如果您将线程数设置为960,则占用率为63%,这就解释了它的工作原理。 尝试将寄存器的数量限制为32 ,并将线程数设置为1024 ,占用率为67%。 要限制寄存器的数量,请使用以下选项: nvcc [...] --maxrregcount=32 I filled the CUDA Occupancy calculator file with th...

为什么〜 - (2 +“2”)是21?(Why ~-(2 + “2”) is 21?)

~-(2 + "2") 0: 2 + "2" (连接)= "22" 1: -"22" (强制)= -22 2: ~-22 (按位NOT)= - ( - 22 + 1)= 21 按位注意任何数字x的产量 - (x + 1)。 例如,〜-5产生4。 ~-(2 + "2") 0: 2 + "2" (Concatenation) = "22" 1: -"22" (Coercion) = -22 2: ~-22 (Bitwise NOT) = -(-22 + 1) = 21 Bitwise NOTing...

Youtube Api playVideo方法在某些移动设备上不起作用(Youtube Api playVideo method doesn't work on some mobile devices)

看起来您正在使用的某些功能(player.playVideo())在移动设备中被禁用。 在我的情况下,在某些Android设备中使用player.playVideo()后,即使点击了播放器,视频也无法播放 https://developers.google.com/youtube/iframe_api_reference?hl=zh-TW#Mobile_considerations 自动播放和脚本播放 在某些移动浏览器(例如Chrome和Safari)中,HTML5元素仅允许在用户交互(例如点击播...

相关文章

更多

Java 流(Stream)、文件(File)和IO

Java 流(Stream)、文件(File)和IO Java.io包几乎包含了所有操作输入、输 ...

Hadoop 自定义InputFormat实现自定义Split

上一篇文章中提到了如何进行RecordReader的重写(见 http://www.linuxidc. ...

java String.split(“.”)和String.split(“|”)的注意事项

查jdk的api你可以发现split的参数是正则表达式,如果你直接使用.或|来切分,是不对的 解决方案 ...

【HDFS】HADOOP DISTRIBUTED FILE SYSTEM

【HDFS】Hadoop DISTRIBUTED FILE SYSTEM THE CAST CLIEN ...

Failed to read auto-increment value from storage engine错误的解决方法

在进行数据的插入时,系统提示Failed to read auto-increment value f ...

用‘button’跟‘text’组合代替‘file’,选择文件后点‘submit’,‘file’的值被清空

各位大虾晚上好,我有个问题想请教你们,我想美化html的file外观,但貌似现在还不能用css直接设计 ...

PHP 中dirname(_file_)

PHP 中dirname(_file_) 2007-5-3 16:00|查看: 19256|评论: ...

xxx is not in the sudoers file解决方法

用sudo时提示&quot;xxx is not in the sudoers file. This ...

file_get_contents 无法读取https的问题解决!

做微信公众平台开发,要通过读取公众平台的一个网址实时获得access_token,用了file_get ...

shell 脚本执行,出现错误bad interpreter: No such file or directory

出现bad interpreter:No such file or directory的原因 是文件格 ...

最新问答

更多

python的访问器方法有哪些

使用方法: class A(object): def foo(self,x): #类实例方法 print "executing foo(%s,%s)"%(self,x) @classmethod def class_foo(cls,x): #类方法 print "executing class_foo(%s,%s)"%(cls,x) @staticmethod def static_foo(x): #静态方法 print "executing static_foo(%s)"%x调用方法: a =

使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)

我认为你必须将两个TableGetway传递给UserTable构造。 你必须改变Module.php看看: public function getServiceConfig() { return array( 'factories' => array( 'User\Model\UserTable' => function($sm) { $userTableGateway = $sm->get('UserTable

透明度错误IE11(Transparency bug IE11)

这是一个渲染错误,由使用透明度触发,使用bootstrap用于在聚焦控件周围放置蓝色光环的box-shadow属性。 可以通过添加以下类覆盖来解决它。 .form-control:hover { -webkit-box-shadow: 0px 0px 5px 0px rgba(0,0,255,1); -moz-box-shadow: 0px 0px 5px 0px rgba(0,0,255,1); box-shadow: 0px 0px 4px 0px rgba(0,0,255,1)

linux的基本操作命令。。。

ls 显示目录 mkdir 建立目录 cd 进入目录

响应navi重叠h1和nav上的h1链接不起作用(Responsive navi overlaps h1 and navi links on h1 isn't working)

将z-index设置为.main-nav这将解决您的重叠问题 .main-nav { position:relative; z-index:9; } set z-index to .main-nav This will fix your overlaping issue .main-nav { position:relative; z-index:9; }

在C中读取文件:“r”和“a +”标志的不同行为(Reading a File in C: different behavior for “r” and “a+” flags)

这是因为模式规范"a"打开一个文件以便追加,文件指针在末尾。 如果您尝试从此处读取,则由于文件指针位于EOF,因此没有数据。 您应该打开"r+"进行阅读和写作。 如果在写入之前读取整个文件,则在写入更多数据时,文件指针将正确定位以追加。 如果这还不够,请探索ftell()和fseek()函数。 That is because the mode spec "a" opens a file for appending, with the file pointer at the end. If you

NFC提供什么样的带宽?(What Kind of Bandwidth does NFC Provide?)

支持空中接口的数据速率是一回事。 在消除协议开销,等待eeprom写入以及所有需要时间的其他内容之后,您看到的数据速率是完全不同的故事。 长话短说,从标签读取或进行对等传输时的实际数据速率峰值约为2.5千字节/秒。 取决于具体的标签或对等技术,它可能比这慢很多。 The supported data-rates of the air-interface are one thing. The data-rate that you see after removing protocol overhe

元素上的盒子阴影行为(box-shadow behaviour on elements)

它看起来像只在Windows上的Chrome的错误。 我在Google Canary (Chrome 63)中也进行了测试,问题依然存在,所以有可能它不会很快修复。 这个问题是由overflow: auto引起的overflow: auto ,在你的情况下,它可以很容易地通过删除或设置为可见(默认)来解决。 但是 ,将鼠标悬停在右侧(顶部和底部)时,会出现滚动条。 一个解决方案可以设置overflow: hidden的身体,所以预期的结果是所需的。 我想指出,这不是一个很好的解决方案,但我建议暂

Laravel检查是否存在记录(Laravel Checking If a Record Exists)

这取决于您是否要以后与用户合作,或仅检查是否存在。 如果要使用用户对象(如果存在): $user = User::where('email', '=', Input::get('email'))->first(); if ($user === null) { // user doesn't exist } 如果你只想检查 if (User::where('email', '=', Input::get('email'))->count() > 0) { // user found

设置base64图像的大小javascript - angularjs(set size of a base64 image javascript - angularjs)

$scope.getData= function () { var reader = new FileReader(); reader.onload = $('input[type=file]')[0].files; var img = new Image(); img.src =(reader.onload[0].result); img.onload = function() { if(this.width > 640