小编hel*_*low的帖子

切换字母(没有字符串或字符串函数)

我想在每次出现在文本中时将"cat"这个词切换成"dog".我不能使用字符串或字符串函数.

我的代码:

#include <stdio.h>

int main()
{   
    int i; // loop counter 
    int size; // size of arry  
    int input[20];
    printf("enter text here\n");  

    while((input[i] = getchar()) != '\n') // input text to the arry
    {
        if(input[i]=='c' && input[i+1]=='a' && input[i+2]=='t') // switching characters
        {
            input[i]='d'; input[i+1]='o'; input[i+2]='g'; 
        }

        i++; 
        size++;  
    }

    i=0; // reset for next loop

    while(i <= size) // printing the text out ofthe arry 
    {
         putchar(input[i]); 
         i++;
    }

    printf("\n"); 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

enter text here                                                                                                                                  
cat …
Run Code Online (Sandbox Code Playgroud)

c arrays text

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

如何创建一个特征作为返回参数的特征方法?

我有一个特征B,它定义了一个函数,该函数返回对实现特征的对象的引用A.

enum Error { }

trait A { }

trait B {
    fn create_a<'a>() -> Result<&'a impl A, Error>;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试编译时,我收到以下错误

error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
  --> src/lib.rs:10:37
   |
10 |     fn create_a<'a>() -> Result<&'a impl A, Error>;
   |                                     ^^^^^^
Run Code Online (Sandbox Code Playgroud)

rust

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

为什么 Rust 需要双重借用 (`&amp;&amp;'a mut T`)

我的代码如下所示

pub enum Cache<'a, T> {
    Pending(&'a dyn FnOnce() -> T),
    Cached(T),
}

impl<'a, T> Cache<'a, T> {
    pub fn get(&self) -> &mut T {
        // This caches and borrows the T
    }
}

impl<'a, T> PartialEq for Cache<'a, T>
    where &'a mut T: PartialEq {

    fn eq(&self, other: &Self) -> bool {
        self.get().eq(other.get())
    }
}
Run Code Online (Sandbox Code Playgroud)

但实施Eq失败:

pub enum Cache<'a, T> {
    Pending(&'a dyn FnOnce() -> T),
    Cached(T),
}

impl<'a, T> Cache<'a, T> {
    pub fn …
Run Code Online (Sandbox Code Playgroud)

types rust borrow-checker borrowing

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

Rust 在使用 push_str() 将一个新字符串连接到另一个字符串时是否会在这个衬里给出错误?

我想连接一个字符串。
在我看来,以下代码应该给出某种恐慌或编译器错误。

let mut s = String::from("abc").push_str("x");
println!("{:?}", s); // Prints ()
Run Code Online (Sandbox Code Playgroud)

但这段代码有效:

let mut s = String::from("abc");
s.push_str("x");  
println!("{:?}", s); // Prints "abcx"
Run Code Online (Sandbox Code Playgroud)

string concatenation rust

0
推荐指数
2
解决办法
122
查看次数

标签 统计

rust ×3

arrays ×1

borrow-checker ×1

borrowing ×1

c ×1

concatenation ×1

string ×1

text ×1

types ×1