Rust:文件中字符串的生命周期

时间:2015-06-14 20:49:27

标签: file io rust

我正在尝试将一些外部GLSL代码读入Rust。阅读工作正常,但我在最终表达式(在Ok(_)分支中)

中遇到了终身问题

错误:s活得不够长

fn read_shader_code(string_path: &str) -> &str {
    let path = Path::new(string_path);
    let display = path.display();

    let mut file = match File::open(&path) {
        Err(why) => panic!("Couldn't open {}: {}", display, Error::description(&why)),
        Ok(file) => file,
    };

    let mut s = String::new();
    match file.read_to_string(&mut s) {
        Err(why) => panic!("couldn't read {}: {}", display, Error::description(&why)),
        Ok(_) => &s,
    }
}

1 个答案:

答案 0 :(得分:2)

一旦函数结束(“s”超出范围),绑定到“s”的字符串将被释放,因此您不能在函数外部返回对其内容的引用。 最好的方法是返回字符串本身:

- (void)viewDidLoad {
    [super viewDidLoad];
}

-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    self.isCurrencySelect = NO;
    [self createCardTypeList];
    self.currencyList = [FinanceUtils currencyCodeListWithAppendedName:NO];
    self.pickerContainerView.hidden = YES;

    [self.cardTypeButton setTitle:CARDTYPENAME forState:UIControlStateNormal];
    [self.currencyButton setTitle:CARDCURRENCYNAME forState:UIControlStateNormal];

    self.cardBackgroundView.layer.cornerRadius = 10.0f;
    self.cardBackgroundView.layer.borderWidth = 2.0f;
    self.cardBackgroundView.layer.borderColor = [UIColor blackColor].CGColor;
    self.cardBackgroundView.backgroundColor = [UIColor colorFromHexString:@"#502CA7"];

    //change placeholder color
    [self.cardNameTextField setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.incomeTextField setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"];

    //set cards value
    self.moneySpentValueLabel.text = @"0";
}

-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self updateButtonsColor];
}

-(void) updateButtonsColor{
    NSArray *buttonsColorArray = [UIColor cardsColorArray];

    for(UIButton *btn in self.buttonsArray){

        btn.layer.borderWidth = 2.0f;

        btn.layer.cornerRadius = btn.frame.size.width/2;

        btn.layer.masksToBounds = YES;
        btn.backgroundColor  = [buttonsColorArray objectAtIndex:btn.tag];
     }
}