rust


How do I fix a missing lifetime specifier?


I have a very simple method. The first argument takes in vector components ("A", 5, 0) and I will compare this to every element of another vector to see if they have the same ( _ , 5 , _) and then print out the found element's string.
Comparing ("A", 5, 0 ) and ("Q", 5, 2) should print out Q.
fn is_same_space(x: &str, y1: i32, p: i32, vector: &Vec<(&str, i32, i32)>) -> (&str) {
let mut foundString = "";
for i in 0..vector.len() {
if y1 == vector[i].1 {
foundString = vector[i].0;
}
}
foundString
}
However, I get this error
error[E0106]: missing lifetime specifier
--> src/main.rs:1:80
|
1 | fn is_same_space(x: &str, y1: i32, p: i32, vector: &Vec<(&str, i32, i32)>) -> (&str) {
| ^ expected lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or one of `vector`'s 2 elided lifetimes
By specifying a lifetime:
fn is_same_space<'a>(x: &'a str, y1: i32, p: i32, vector: &'a Vec<(&'a str, i32, i32)>) -> (&'a str)
This is only one of many possible interpretations of what you might have meant for the function to do, and as such it's a very conservative choice - it uses a unified lifetime of all the referenced parameters.
Perhaps you wanted to return a string that lives as long as x or as long as vector or as long as the strings inside vector; all of those are potentially valid.
I strongly recommend that you go back and re-read The Rust Programming Language. It's free, and aimed at beginners to Rust, and it covers all the things that make Rust unique and are new to programmers. Many people have spent a lot of time on this book and it answers many beginner questions such as this one.
Specifically, you should read the chapters on:
ownership
references and borrowing
lifetimes
There's even a second edition in the works, with chapters like:
Understanding Ownership
Generic Types, Traits, and Lifetimes
For fun, I'd rewrite your code using iterators:
fn is_same_space<'a>(y1: i32, vector: &[(&'a str, i32, i32)]) -> &'a str {
vector.iter()
.rev() // start from the end
.filter(|item| item.1 == y1) // element that matches
.map(|item| item.0) // first element of the tuple
.next() // take the first (from the end)
.unwrap_or("") // Use a default value
}
Removed the unneeded parameters.
Using an iterator avoids the overhead of bounds checks, and more clearly exposes your intent.
Why is it discouraged to accept a reference to a String (&String) or Vec (&Vec) as a function argument?
Rust does not use camelCase variable names.
I assume that you do want to return the string from inside vector.
Remove the redundant parens on the return type
So the problem comes from the fact that vector has two inferred lifetimes, one for vector itself (the &Vec part) and one for the &str inside the vector. You also have an inferred lifetime on x, but that really inconsequential.
To fix it, just specify that the returned &str lives as long as the &str in the vector:
fn is_same_space<'a>( // Must declare the lifetime here
x: &str, // This borrow doesn't have to be related (x isn't even used)
y1: i32, // Not borrowed
p: i32, // Not borrowed or used
vector: &'a Vec<(&'a str, i32, i32)> // Vector and some of its data are borrowed here
) -> &'a str { // This tells rustc how long the return value should live
...
}

Related Links

What's the purpose of SizeHint in Iterator::unzip?
Repetitive trait bounds on generic structs [duplicate]
Choose to borrow or pass ownership without duplicating code in Rust
How to get the name of current program without the directory part?
Changing key of HashMap from child method
Cannot build a delete function for a binary search tree in Rust because the borrowed value does not live long enough
Why does AtomicUsize not implement Send?
How can I define a list of functions to call? [duplicate]
How can I tell if a Rust library is deprecated?
error: non-scalar cast: `core::option::Option<i32>` as `usize`
Lifetime of variable in map/flat_map in Rust
Can associated constants be used to initialize fixed size arrays?
Why do Arc and Mutex allow me to change the value of an immutable variable?
Unable to download a package via cargo — timeout
“borrowed value does not live long enough” seems to blame the wrong thing
Is the destructor of Arc guaranteed to be called before upgrading a Weak reference will return None?

Categories

HOME
magento2
weblogic12c
gaming
freeradius
bokeh
d3.js
devexpress
consul
dronekit-python
mathematical-optimization
gallery
cypher
tibco
material-components
static-analysis
stack-overflow
hystrix
solution
xades4j
tiff
mailmerge
stimulsoft
webstore
renderscript
cmake-gui
libgit2
jitsi
sharedpreferences
kaggle
qa
fluent-migrator
channel
backendless
sap-lumira
bonita
spring-annotations
cube
unmarshalling
envoy
autodesk-model-derivative
kendo-listview
des
subclassing
numerics
microkernel
windows-store
distributed-caching
fluid-mac-app-engine
daz3d
absolute
viewmodel
lightning-workbench
punctuation
popen
patternlab.io
nunit-console
carmen
perforce-integrate
android-syncadapter
odp.net-managed
processor
urbit
okta-api
voronoi
ambiguity
css-paged-media
uitest
innerhtml
fiware-bosun
pass-by-value
fat32
encryption-symmetric
rubber
ildasm
wicket-1.5
image-rotation
inputbox
igor
xhprof
jquery-mobile-flipswitch
ecos
webautomation
distributed-r
screwturn
senchatouch-2.4
rails-api
zend-search-lucene
miglayout
ctp
visual-c++-2005
colon
grails-2.3
disjoint-union
ldif
microformats
blobstorage
aero
cmath
semantic-merge
onconfigurationchanged
wndproc
thejit
multidrop-bus
fbml
differentiation
server-variables
asp.net-mvc-views
dm
ppc
data-retrieval
gui-designer

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App