lifetime

Lifetime error when creating a function that returns a value implementing serde::Deserialize

流过昼夜 提交于 2019-11-26 19:11:25
I'm using serde and serde_json 1.0 to decode data from a base64 string: fn from_base64_str<T: Deserialize>(string: &str) -> T { let slice = decode_config(string, URL_SAFE).unwrap(); serde_json::from_slice(&slice).unwrap() } When I compile, I got this: error[E0106]: missing lifetime specifier --> src/main.rs:6:23 | 6 | fn from_base64_str<T: Deserialize>(string: &str) -> T { | ^^^^^^^^^^^ expected lifetime parameter Checking the serde doc, Deserialize is defined as: pub trait Deserialize<'de>: Sized { So I added the lifetime: fn from_base64_str<'de, T: Deserialize<'de>>(string: &str) -> T { let

How to set lifetime of session

你。 提交于 2019-11-26 18:45:21
How to set session lifetime in PHP? I Want to set it to forever as long as the request is exist. The request is AJAX. My PHP code that handle AJAX request is: // AJAX.php <?php session_start(); $_SESSION['counter'] = $_SESSION['counter'] + 1; header('Content-type: application/json'); echo json_encode(array('tick' => $_SESSION['counter'])); ?> and the JavaScript: $(document).ready(function() { function check() { getJSON('ajax.php'); } function getJSON(url) { return $.getJSON( url, function(data) { $("#ticker").html(data.tick); } ); } setInterval(function() { check(); }, 10000); // Tick every 10

How do I write the lifetimes for references in a type constraint when one of them is a local reference?

南楼画角 提交于 2019-11-26 18:00:58
I have a trait Matrix and generic function semi_def<T: Matrix>(x: &T) that I would like to operate on that trait. The function requires an operator trait, say Mul , be implemented on T . However, I can't seem to make the lifetimes happy if one of the references is to a local variable. How do I write the lifetimes for references in the type constraint when one of them is just a local temporary reference? use std::ops::Mul; trait Matrix: Clone { fn transpose(self) -> Self; } #[derive(Clone)] struct DenseMatrix { n_rows: usize, n_columns: usize, elements: Vec<f64>, } impl Matrix for DenseMatrix {

Iterator returning items by reference, lifetime issue

大憨熊 提交于 2019-11-26 17:54:22
I have a lifetime issue, I'm trying to implement an iterator returning its items by reference, here is the code: struct Foo { d: [u8; 42], pos: usize } impl<'a> Iterator<&'a u8> for Foo { fn next<'a>(&'a mut self) -> Option<&'a u8> { let r = self.d.get(self.pos); if r.is_some() { self.pos += 1; } r } } fn main() { let mut x = Foo { d: [1; 42], pos: 0 }; for i in x { println!("{}", i); } } However this code doesn't compile properly, I get an issue related to the lifetime of parameters, here is the corresponding error: $ rustc test.rs test.rs:8:5: 14:6 error: method `next` has an incompatible

lifetime of a std::initializer_list return value

╄→гoц情女王★ 提交于 2019-11-26 16:39:59
问题 GCC's implementation destroys a std::initializer_list array returned from a function at the end of the return full-expression. Is this correct? Both test cases in this program show the destructors executing before the value can be used: #include <initializer_list> #include <iostream> struct noisydt { ~noisydt() { std::cout << "destroyed\n"; } }; void receive( std::initializer_list< noisydt > il ) { std::cout << "received\n"; } std::initializer_list< noisydt > send() { return { {}, {}, {} }; }

Lifetime troubles sharing references between threads

断了今生、忘了曾经 提交于 2019-11-26 15:32:30
I've got a thread that launches worker threads, all are expected to live forever. Each worker thread maintains it's own list of Socket s. Some operations require that I traverse all sockets currently alive, but I'm having trouble with lifetimes trying to create a master list of sockets containing a pointer to a socket owned by another list. use std::{str, thread}; use std::thread::JoinHandle; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, Mutex}; use std::ops::DerefMut; use std::sync::mpsc::{channel, Sender, Receiver, TryRecvError}; use self:

How do I implement the Add trait for a reference to a struct?

自作多情 提交于 2019-11-26 14:40:09
I made a two element Vector struct and I want to overload the + operator. I made all my functions and methods take references, rather than values, and I want the + operator to work the same way. impl Add for Vector { fn add(&self, other: &Vector) -> Vector { Vector { x: self.x + other.x, y: self.y + other.y, } } } Depending on which variation I try, I either get lifetime problems or type mismatches. Specifically, the &self argument seems to not get treated as the right type. I have seen examples with template arguments on impl as well as Add , but they just result in different errors. I found

Why is the bound `T: &#39;a` required in order to store a reference `&&#39;a T`?

蓝咒 提交于 2019-11-26 14:20:11
问题 Given this code: struct RefWrapper<'a, T> { r: &'a T, } ... the compiler complains: error: the parameter type T may not live long enough consider adding an explicit lifetime bound T: 'a so that the reference type &'a T does not outlive the data it points at. I've seen this error multiple times already and so far I just listened to the compiler and everything worked out fine. However, thinking more about it, I don't understand why I have to write T: 'a . As far as I understand, it is already

“constructing” a trivially-copyable object with memcpy

ぐ巨炮叔叔 提交于 2019-11-26 13:46:51
In C++, is this code correct? #include <cstdlib> #include <cstring> struct T // trivially copyable type { int x, y; }; int main() { void *buf = std::malloc( sizeof(T) ); if ( !buf ) return 0; T a{}; std::memcpy(buf, &a, sizeof a); T *b = static_cast<T *>(buf); b->x = b->y; free(buf); } In other words, is *b an object whose lifetime has begun? (If so, when did it begin exactly?) This is unspecified which is supported by N3751: Object Lifetime, Low-level Programming, and memcpy which says amongst other things: The C++ standards is currently silent on whether the use of memcpy to copy object

What should be the lifetime of an NHibernate session?

无人久伴 提交于 2019-11-26 13:05:19
问题 I\'m new to NHibernate, and have seen some issues when closing sessions prematurely. I\'ve solved this temporarily by reusing sessions instead of opening a session per transaction. However, I was under the impression that opening sessions each time you need them was the recommended approach for session lifetime management. No? So; what is the recommended way of handling sessions? What should their lifetime be? One session pr transaction? One singleton session to handle everything? Or what?