如何将浮点值转换为String?无论出于何种原因,我可以找到的文档和所有在线资源只关注其他方面.
let value: f32 = 17.65;
let value_as_str: String = .....
Run Code Online (Sandbox Code Playgroud) 我有vec一些结构类型,我想改变向量中第一个元素的一些字段.我怎样才能做到这一点?
例:
struct SomeType {
some_value: i32,
}
fn main() {
let mut vec = Vec::new();
let mut t = SomeType { some_value: 45 };
vec.push(t);
println!("Old value: {}", vec.first().unwrap().some_value);
vec.first().unwrap().some_value += 1;
println!("New value: {}", vec.first().unwrap().some_value);
}
Run Code Online (Sandbox Code Playgroud)
这无法编译:
error: cannot assign to immutable field
--> vec.rs:15:2
|
15 | vec.first().unwrap().some_value += 1;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot mutably borrow immutable field
Run Code Online (Sandbox Code Playgroud)
我无法理解Rust中的可变性东西; 这里有什么正确的方法?
考虑以下:
fn main() {
let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let even = input.iter().filter(|&x| x % 2 == 0).collect::<Vec<&i32>>();
for x in &even {
println!("{}", x);
}
}
Run Code Online (Sandbox Code Playgroud)
此输出2 4 6 8 10(如预期)。但是,如果我只想要前 3 项怎么办?是否有可能以某种方式限制返回值collect,而不需要先收集所有东西,然后扔掉一些物品?
我正在尝试将 C++ 项目链接到 RCpp 库;该文件名为Rcpp.so,而不是 linux-default libRcpp.so。此外,图书馆位于非标准位置/usr/lib/R/site-library/Rcpp/libs。
find_library所以我尝试使用和的组合target_link_libraries:
cmake_minimum_required(VERSION 3.8)
project("R-Tests")
find_library(RCPP
NAMES Rcpp.so
HINTS /usr/lib/R/site-library/Rcpp/libs
)
if (NOT RCPP)
message(FATAL_ERROR "Could not find Rcpp - exiting.")
else()
message("Found Rcpp: " ${RCPP})
endif()
# test target
add_executable(rcpptest main.cpp)
target_link_libraries(rcpptest ${RCPP})
Run Code Online (Sandbox Code Playgroud)
配置工作正常,CMake 输出:
Found Rcpp: /usr/lib/R/site-library/Rcpp/libs/Rcpp.so
Run Code Online (Sandbox Code Playgroud)
然而,在构建过程中,CMake 传递-lRcpp给编译器,这会导致编译失败,因为库文件没有命名,libRcpp.so而是Rcpp.so:
[100%] Linking CXX executable rcpptest
/usr/bin/cmake -E cmake_link_script CMakeFiles/rcpptest.dir/link.txt --verbose=1
c++ CMakeFiles/rcpptest.dir/main.cpp.o -o rcpptest -L/usr/lib/R/site-library/Rcpp/libs -Wl,-rpath,/usr/lib/R/site-library/Rcpp/libs -lRcpp
/usr/bin/ld: cannot …Run Code Online (Sandbox Code Playgroud) 我想检查测试中具有字段的枚举,而现在暂时忽略字段的实际值。
考虑以下示例:
enum MyEnum {
WithoutFields,
WithFields { field: String },
}
fn return_with_fields() -> MyEnum {
MyEnum::WithFields {
field: "some string".into(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example() {
assert_eq!(return_with_fields(), MyEnum::WithFields {..});
}
}
Run Code Online (Sandbox Code Playgroud)
我想assert_eq!在这里使用,但是编译器告诉我:
enum MyEnum {
WithoutFields,
WithFields { field: String },
}
fn return_with_fields() -> MyEnum {
MyEnum::WithFields {
field: "some string".into(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example() {
assert_eq!(return_with_fields(), MyEnum::WithFields {..});
}
} …Run Code Online (Sandbox Code Playgroud) 基于这个问题,我尝试了一个is_vector特点:
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
struct is_vector {
constexpr static bool value = false;
};
template<typename T>
struct is_vector<std::vector<T>> {
constexpr static bool value = true;
};
int main() {
int A;
vector<int> B;
cout << "A: " << is_vector<decltype(A)>::value << endl;
cout << "B: " << is_vector<decltype(B)>::value << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
A: 0
B: 1
Run Code Online (Sandbox Code Playgroud)
这按预期工作.然而,当我试图把这个小的辅助函数,is_vector返回false为B:
template<typename T>
constexpr bool isVector(const T& …Run Code Online (Sandbox Code Playgroud) 在Rust中,很容易创建IpAddr一个IpV4Addr:
let ipv4 = IpV4Addr::new(127,0,0,1);
let ip = IpAddr::V4(ipv4);
Run Code Online (Sandbox Code Playgroud)
但似乎没有办法回来:
if ip.is_ipv4() {
let ipv4: IpV4Addr = .....?
}
Run Code Online (Sandbox Code Playgroud)
原因是我需要在某个时刻(通过IPv4::octets)访问IPv4地址的八位字节以通过网络传输它们.但是,我想IpAddr在应用程序的其他部分使用更通用的表示,因为我希望将来实现IPv6,因此使网络代码不是特定于IPv4的.
我想使用 hyper 创建一个小型 Rust HTTP 代理,它接受请求、转发请求并转储请求 + 正文。
基于这个例子,代理部分工作正常。
但是,我不能简单地复制和打印请求正文。我的主要问题是请求正文不能简单地复制到Vec<u8>. 我无法deconstruct请求读取正文然后稍后创建它,因为无法将解构的标头添加到新请求中。
以下代码显示了我的最小 HTTP 代理示例:
extern crate futures;
extern crate hyper;
extern crate tokio_core;
use futures::{Future, Stream};
use hyper::{Body, Client, StatusCode};
use hyper::client::HttpConnector;
use hyper::header::{ContentLength, ContentType};
use hyper::server::{Http, Request, Response, Service};
use tokio_core::reactor::Core;
type HTTPClient = Client<HttpConnector, Body>;
struct Server {
client: HTTPClient,
}
impl Server {
pub fn new(client: HTTPClient) -> Server {
Server { client: client }
}
}
impl Service for Server …Run Code Online (Sandbox Code Playgroud) Rust显然是一种新语言(0.8).它看起来很有趣,我开始关注它.我提到了一些软件float被改为f64,所以我想找到数据类型的位置,包括float定义的.我找不到任何非常具体的东西.我找到了:
有三个浮点类型:
float,f32,和f64.浮点数写入0.0,1e6或2.1e-4.与整数一样,浮点文字也被推断为正确的类型.后缀f,f32和f64.
我猜" 浮动 "或" f "是16位.
在更广泛的说明(我不是计算机科学家),是不是真的值得所有这些小的数据类型,如瞎搞int,int32,int64,f,f32,f64(仅举几例).我可以理解一些语言,例如.字节类型,因为字符串是一个相当复杂的类型.对于数字类型,我认为它只会产生不必要的复杂性.为什么不有i64和f64,并呼吁他们诠释和漂浮(或i64和f64,以应付未来的变化,或者有浮动和INT默认这些).
也许有一些低级程序需要较小的值,但为什么不保留那些需要它们的程序使用并将它们排除在核心之外呢?我发现从例如转换是不必要的苦差事.int对i64等,它有什么真正实现?或者,将它们保留在"核心"中,但默认为64位类型.64位类型显然是必要的,而其余只是特定情况(IMO)所必需的.
我正试图SDL_PollEvent从C库中调用该函数SDL2.我知道已有包装,但我想创建自己的包装,只是为了学习.该函数需要一个指向此C联合的指针:
typedef union{
Uint8 type;
SDL_ActiveEvent active;
SDL_KeyboardEvent key;
SDL_MouseMotionEvent motion;
SDL_MouseButtonEvent button;
SDL_JoyAxisEvent jaxis;
SDL_JoyBallEvent jball;
SDL_JoyHatEvent jhat;
SDL_JoyButtonEvent jbutton;
SDL_ResizeEvent resize;
SDL_ExposeEvent expose;
SDL_QuitEvent quit;
SDL_UserEvent user;
SDL_SysWMEvent syswm;
} SDL_Event;
Run Code Online (Sandbox Code Playgroud)
我已经导入了这样的函数:
#[link(name = "SDL2")]
extern "C" {
fn SDL_PollEvent(event: *mut SdlEvent) -> libc::c_int;
}
Run Code Online (Sandbox Code Playgroud)
并声明了这样的类型:
type SdlEvent = [u8; 56];
Run Code Online (Sandbox Code Playgroud)
现在我可以调用SDL_Pollevent并检索typeunion 的值:
// According to sizeof(SDL_Event), the unit is 56 bytes
let mut sdl_event: SdlEvent = [0; 56];
unsafe …Run Code Online (Sandbox Code Playgroud)