小编XAM*_*cky的帖子

从字符串中获取单个字符

我想得到一个第一个角色std::str.该方法char_at()目前是不稳定的,如slice_charsstd::string::String.

我目前唯一提出的选择如下.

let text = "hello world!";
let char_vec:Vec<char> = text.chars().collect();
let ch = char_vec[0];
Run Code Online (Sandbox Code Playgroud)

但这对于获得单个字符似乎过分,而不是使用向量的其余部分.

string rust

37
推荐指数
3
解决办法
2万
查看次数

如何将格式良好的表格打印到控制台?

我有一个程序打印出应该打印成看起来像表的格式的数据.但是,当数字长于2时,表会中断.我知道width参数std::fmt,但是我无法理解它.

当前输出:

---------------------------------------
| total | blanks: | comments: | code: |
---------------------------------------
|  0   |    0    |    0     |    0  |
|  77   |    0    |    3     |    74  |
|  112   |    0    |    6     |    106  |
|  178   |    0    |    6     |    172  |
|  218   |    0    |    7     |    211  |
|  289   |    0    |    8     |    281  |
|  380   |    0    |    9     |    371  | …
Run Code Online (Sandbox Code Playgroud)

println rust

13
推荐指数
2
解决办法
3628
查看次数

如何使VS代码构建和运行Rust程序?

我一直在使用VS Code,我想知道如何构建一个task.json具有这些命令的文件.cargo build,cargo run [ARGS] cargo run --release -- [ARGS]

我试着做一个与文件task.json.我一直在No such subcommand犯错.

样品:

{
"version": "0.1.0",
// The command is tsc. Assumes that tsc has been installed using npm install -g typescript
"command": "cargo",

// The command is a shell script
"isBuildCommand": true,

// Show the output window only if unrecognized errors occur. 
"showOutput": "silent",

"tasks": [{
   "taskName": "run test",
   "version": "0.1.0",
   "command": "run -- --exclude-dir=node_modules …
Run Code Online (Sandbox Code Playgroud)

rust visual-studio-code

7
推荐指数
1
解决办法
5682
查看次数

使用Serde将两种类型转换为单一类型

我正在编写一个程序,它挂钩到一个发回JSON的Web服务.

当某个属性不存在时,它提供一个空对象,其所有字段为空字符串,而不是排除该值.当属性存在时,一些属性是u64.我怎么能拥有它以便Serde处理这个案子?

Rust Structs

#[derive(Clone, Debug, Deserialize)]
struct WebResponse {
    foo: Vec<Foo>,
}

#[derive(Clone, Debug, Deserialize)]
struct Foo {
    points: Points,
}

#[derive(Clone, Debug, Deserialize)]
struct Points {
    x: u64,
    y: u64,
    name: String,
}
Run Code Online (Sandbox Code Playgroud)

示例JSON

{
    "foo":[
        {
            "points":{
                "x":"",
                "y":"",
                "name":""
            }
        },
        {
            "points":{
                "x":78,
                "y":92,
                "name":"bar"
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

json rust deserialization serde

6
推荐指数
2
解决办法
604
查看次数

如何检查给定路径是文件还是目录?

我正在构建一个应该能够同时获取文件(*.*)和目录(./,..)的路径的程序.我希望能够检查提供的路径是文件还是目录.

directory file-io file path rust

5
推荐指数
2
解决办法
1893
查看次数

在Serde中处理混合对象数组

扩展我之前的问题,你如何处理包含混合的数组structs?我试过看serde_json::Value源头.但是它没有处理两种不同的情况structs.

我不能简单地合并它们,并且在它们的属性上使用Options,因为这会使单个struct变得难以处理,并且它们必须是不同的.

锈结构

#[derive(Clone, Debug, Deserialize)]
struct WebResponse {
    foo: Vec<Structs>,
}

enum Structs {
    Foo(Foo),
    Bar(Bar),
}

#[derive(Clone, Debug, Deserialize)]
struct Foo {
    name: String,
    baz: Vec<String>,
}

#[derive(Clone, Debug, Deserialize)]
struct Bar {
    quux: u64
}
Run Code Online (Sandbox Code Playgroud)

示例JSON

{
    "foo": [
        {
            "name": "John",
            "baz": ["Lorem", "Ipsum"]
        },
        {
            "quux": 17
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

serialization json rust serde

5
推荐指数
1
解决办法
676
查看次数

如何在Rust中调用Swift函数?

我有一个用Swift编写的函数,我想从Rust调用。我尝试通过Objective-C公开它,但是由于ld说它找不到而继续出错_foo。通过将Rust项目编译为staticlib,Rust项目链接到Swift项目。

foo.h

#pragma once

#include <stdint.h>

uint8_t foo_bridge(uint8_t);
Run Code Online (Sandbox Code Playgroud)

foo.m

#import <Foundation/Foundation.h>
#import <Foo-Swift.h>

uint8_t foo_bridge(uint8_t byte) {
    return foo(byte);
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特

public func foo(byte: UInt8) -> UInt8 {
    return byte * 2
}
Run Code Online (Sandbox Code Playgroud)

src / lib.rs

public func foo(byte: UInt8) -> UInt8 {
    return byte * 2
}
Run Code Online (Sandbox Code Playgroud)

Bar-Bridging-Header.h

extern "C" {
    pub fn foo_bridge(byte: u8) -> u8;
}
Run Code Online (Sandbox Code Playgroud)

货代

[package]
name = "foo"
version = "0.1.0"

[lib]
name = "foo"
crate-type = ["staticlib"]
Run Code Online (Sandbox Code Playgroud)

objective-c ffi rust swift

5
推荐指数
1
解决办法
736
查看次数

程序宏可以在结构上派生添加其他派生吗?

程序宏派生是否可以将来自其他 crate 的派生添加到它派生的结构中?

库文件

#[derive(Combined)]
struct Foo;
Run Code Online (Sandbox Code Playgroud)

派生_combined.rs

#[macro_use] extern crate quote;
extern crate proc_macro2;
extern crate proc_macro;
extern crate syn;

use proc_macro::TokenStream;

#[proc_macro_derive(Combined)]
pub fn my_macro(input: TokenStream) -> TokenStream {
    let input: DeriveInput = syn::parse(input).unwrap();
    let ident = input.ident;
    let expanded = quote! {
        #[derive(Clone, Debug)]
        struct #ident;
    };

    expanded.into()
}
Run Code Online (Sandbox Code Playgroud)

macros rust

5
推荐指数
2
解决办法
1614
查看次数

在`fmt :: Display`中递归打印struct

我目前正在实现fmt::Display一个结构,以便它将打印到控制台.然而,struct有一个字段,它是Vec它的类型.

结构

pub struct Node<'a> {
    pub start_tag: &'a str,
    pub end_tag: &'a str,
    pub content: String,
    pub children: Vec<Node<'a>>,
}
Run Code Online (Sandbox Code Playgroud)

当前fmt ::显示(无效)

impl<'a> fmt::Display for Node<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "START TAG: {:?}", self.start_tag);
        write!(f, "CONTENT: {:?}", self.content);
        for node in self.children {
            write!(f, "CHILDREN:\n\t {:?}", node);
        }
        write!(f, "END TAG: {:?}", self.end_tag);
    }
}
Run Code Online (Sandbox Code Playgroud)

期望的输出

START TAG: "Hello"
CONTENT: ""
CHILDREN:
   PRINTS CHILDREN WITH INDENT
END TAG: "World"
Run Code Online (Sandbox Code Playgroud)

console struct println rust

4
推荐指数
1
解决办法
559
查看次数

在 powershell 退出时运行脚本

我将如何运行可在exit命令或 shell 关闭上运行的 powershell 脚本。我希望这个脚本在每个关闭的 shell 上运行,而不仅仅是一个 shell。

脚本

windows powershell

3
推荐指数
2
解决办法
4811
查看次数

Swift TableViewCell xib 没有约束

我有两个TableViews,当我设计原件时,我使用情节提要中的原型单元来设计它,为了使其可重复使用,我尝试将其拉出.xib并加载它。cellID.xib然而,当它被加载时,它在运行时失去了所有的约束,一切都在彼此之上。

表视图控制器

let cellIdentifier = "cellID"
override func viewDidLoad() {
    super.viewDidLoad()

    tableView.register(UINib(nibName: cellIdentifier, bundle: nil), forCellReuseIdentifier: cellIdentifier)
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 300
}
Run Code Online (Sandbox Code Playgroud)

故事板中的原型单元格(用于工作)

原型细胞

复制粘贴到 XIB 时的单元格

xib细胞

约束

对细胞的限制

XIB 视图层次结构

xib 视图层次结构

xcode uitableview xib ios uistoryboard

3
推荐指数
1
解决办法
3629
查看次数

从if语句中返回值具有"不匹配类型"错误

在下面的函数中,我匹配a的第一个完整字符&str,如果它是a *,-或者 _是否是返回字符的那个字符,并且_我想要检查该字符是否为空格,'a'否则返回.

fn print_character(text: &str) {
    let character: char = match text.chars().nth(0).unwrap() {
        ch @ '*' | ch @ '-' | ch @ '_' => ch,
        ch @ _ => {
            if !ch.is_whitespace() {
                return 'a';
            }
            ' '
        }
    };

    println!("{}", character);
}
Run Code Online (Sandbox Code Playgroud)

当我运行代码时,我得到以下错误:

error[E0308]: mismatched types
 --> src/main.rs:6:24
  |
6 |                 return 'a';
  |                        ^^^ expected (), found char
  |
  = note: expected type `()`
             found type …
Run Code Online (Sandbox Code Playgroud)

rust

1
推荐指数
1
解决办法
2445
查看次数