What should the return type be for a method that returns &str or new string with the lifetime of the...
I want to create an id
method which either returns an id, which is a struct attribute, or a new string.
What should be my return type? &str
for returning a struct attribute self.title
, but then what is the return type of a new string with lifetime of the calling scope?
fn id(&self) -> &str {
match self.type {
PageType::Type1 => format!("{}-{}", self.title, self.page_num),
PageType::Type2 => &self.title,
}
}
rust
add a comment |
I want to create an id
method which either returns an id, which is a struct attribute, or a new string.
What should be my return type? &str
for returning a struct attribute self.title
, but then what is the return type of a new string with lifetime of the calling scope?
fn id(&self) -> &str {
match self.type {
PageType::Type1 => format!("{}-{}", self.title, self.page_num),
PageType::Type2 => &self.title,
}
}
rust
add a comment |
I want to create an id
method which either returns an id, which is a struct attribute, or a new string.
What should be my return type? &str
for returning a struct attribute self.title
, but then what is the return type of a new string with lifetime of the calling scope?
fn id(&self) -> &str {
match self.type {
PageType::Type1 => format!("{}-{}", self.title, self.page_num),
PageType::Type2 => &self.title,
}
}
rust
I want to create an id
method which either returns an id, which is a struct attribute, or a new string.
What should be my return type? &str
for returning a struct attribute self.title
, but then what is the return type of a new string with lifetime of the calling scope?
fn id(&self) -> &str {
match self.type {
PageType::Type1 => format!("{}-{}", self.title, self.page_num),
PageType::Type2 => &self.title,
}
}
rust
rust
edited Jan 4 at 7:36
Ben
asked Jan 2 at 7:21
BenBen
9,18121115
9,18121115
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
There are three ways you can implement this, with different trade-offs.
Return an owned string
You return String
and use self.title.clone()
.
- Pros: Simple.
- Cons: Allocates a new string on every call, even in the simple case.
Use when you have no reason to think that this might become a performance issue, and you want the simplicity of simply returning String
.
Store the id in the struct
Build it in the constructor function. (Building it on-demand is also possible, but incurs complicated lifetime issues.) Return a &str
. There is hardly ever a good reason to use &String
.
- Pros: Very cheap call.
- Cons: Need to store the id. Need to keep it up-to-date when the
title
orpage_num
fields change.
Use if accessed very frequently.
Return a Cow
This type is capable of representing either a borrowed or an owned thing, and via deref coercion acts like the borrowed thing in usage.
fn id(&self) -> Cow<str> {
match self.ty {
PageType::Type1 => Cow::Owned(format!("{}-{}", self.title, self.page_num)),
PageType::Type2 => Cow::Borrowed(&self.title),
}
}
- Pros: Efficient in the simple case. Doesn't increase struct size. Doesn't need complicated code to maintain the id.
- Cons: The usage is slightly more complicated, depending on what the user does with the result. Still allocates a new string in the complex case.
This makes a good default to use, unless you really want to keep the API as simple as possible.
2
"you could return a Cow, but that complicates usage of the method" : Isn't that the perfect use case for aCow
? Your comment makes it look like it's not the best solution here and I fear it might be badly interpreted.
– Denys Séguret
Jan 2 at 8:28
3
The perfect use case forCow
is when the efficiency gain is worth the usability loss. Since I don't know what the use case is, I can't say what the best way is. But I could formulate the post in a more neutral manner.
– Sebastian Redl
Jan 2 at 10:01
I don't understand what you mean by usability loss, Cow has been design to be a user friendly tool. Also in my opinion the most important is that cow feature have a overheat, people often forget that, small I agree, but always keep in mind that some feature doesn't come for free. (but that a free abstraction ofc)
– Stargateur
Jan 2 at 10:08
1
I've rewritten the post to be more balanced. The usability loss comes from having a wrapper. Yes, deref coercion means that many usages are the same, but under some circumstances, the user actually has to understand what having a cow means.
– Sebastian Redl
Jan 2 at 10:14
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54002638%2fwhat-should-the-return-type-be-for-a-method-that-returns-str-or-new-string-with%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
There are three ways you can implement this, with different trade-offs.
Return an owned string
You return String
and use self.title.clone()
.
- Pros: Simple.
- Cons: Allocates a new string on every call, even in the simple case.
Use when you have no reason to think that this might become a performance issue, and you want the simplicity of simply returning String
.
Store the id in the struct
Build it in the constructor function. (Building it on-demand is also possible, but incurs complicated lifetime issues.) Return a &str
. There is hardly ever a good reason to use &String
.
- Pros: Very cheap call.
- Cons: Need to store the id. Need to keep it up-to-date when the
title
orpage_num
fields change.
Use if accessed very frequently.
Return a Cow
This type is capable of representing either a borrowed or an owned thing, and via deref coercion acts like the borrowed thing in usage.
fn id(&self) -> Cow<str> {
match self.ty {
PageType::Type1 => Cow::Owned(format!("{}-{}", self.title, self.page_num)),
PageType::Type2 => Cow::Borrowed(&self.title),
}
}
- Pros: Efficient in the simple case. Doesn't increase struct size. Doesn't need complicated code to maintain the id.
- Cons: The usage is slightly more complicated, depending on what the user does with the result. Still allocates a new string in the complex case.
This makes a good default to use, unless you really want to keep the API as simple as possible.
2
"you could return a Cow, but that complicates usage of the method" : Isn't that the perfect use case for aCow
? Your comment makes it look like it's not the best solution here and I fear it might be badly interpreted.
– Denys Séguret
Jan 2 at 8:28
3
The perfect use case forCow
is when the efficiency gain is worth the usability loss. Since I don't know what the use case is, I can't say what the best way is. But I could formulate the post in a more neutral manner.
– Sebastian Redl
Jan 2 at 10:01
I don't understand what you mean by usability loss, Cow has been design to be a user friendly tool. Also in my opinion the most important is that cow feature have a overheat, people often forget that, small I agree, but always keep in mind that some feature doesn't come for free. (but that a free abstraction ofc)
– Stargateur
Jan 2 at 10:08
1
I've rewritten the post to be more balanced. The usability loss comes from having a wrapper. Yes, deref coercion means that many usages are the same, but under some circumstances, the user actually has to understand what having a cow means.
– Sebastian Redl
Jan 2 at 10:14
add a comment |
There are three ways you can implement this, with different trade-offs.
Return an owned string
You return String
and use self.title.clone()
.
- Pros: Simple.
- Cons: Allocates a new string on every call, even in the simple case.
Use when you have no reason to think that this might become a performance issue, and you want the simplicity of simply returning String
.
Store the id in the struct
Build it in the constructor function. (Building it on-demand is also possible, but incurs complicated lifetime issues.) Return a &str
. There is hardly ever a good reason to use &String
.
- Pros: Very cheap call.
- Cons: Need to store the id. Need to keep it up-to-date when the
title
orpage_num
fields change.
Use if accessed very frequently.
Return a Cow
This type is capable of representing either a borrowed or an owned thing, and via deref coercion acts like the borrowed thing in usage.
fn id(&self) -> Cow<str> {
match self.ty {
PageType::Type1 => Cow::Owned(format!("{}-{}", self.title, self.page_num)),
PageType::Type2 => Cow::Borrowed(&self.title),
}
}
- Pros: Efficient in the simple case. Doesn't increase struct size. Doesn't need complicated code to maintain the id.
- Cons: The usage is slightly more complicated, depending on what the user does with the result. Still allocates a new string in the complex case.
This makes a good default to use, unless you really want to keep the API as simple as possible.
2
"you could return a Cow, but that complicates usage of the method" : Isn't that the perfect use case for aCow
? Your comment makes it look like it's not the best solution here and I fear it might be badly interpreted.
– Denys Séguret
Jan 2 at 8:28
3
The perfect use case forCow
is when the efficiency gain is worth the usability loss. Since I don't know what the use case is, I can't say what the best way is. But I could formulate the post in a more neutral manner.
– Sebastian Redl
Jan 2 at 10:01
I don't understand what you mean by usability loss, Cow has been design to be a user friendly tool. Also in my opinion the most important is that cow feature have a overheat, people often forget that, small I agree, but always keep in mind that some feature doesn't come for free. (but that a free abstraction ofc)
– Stargateur
Jan 2 at 10:08
1
I've rewritten the post to be more balanced. The usability loss comes from having a wrapper. Yes, deref coercion means that many usages are the same, but under some circumstances, the user actually has to understand what having a cow means.
– Sebastian Redl
Jan 2 at 10:14
add a comment |
There are three ways you can implement this, with different trade-offs.
Return an owned string
You return String
and use self.title.clone()
.
- Pros: Simple.
- Cons: Allocates a new string on every call, even in the simple case.
Use when you have no reason to think that this might become a performance issue, and you want the simplicity of simply returning String
.
Store the id in the struct
Build it in the constructor function. (Building it on-demand is also possible, but incurs complicated lifetime issues.) Return a &str
. There is hardly ever a good reason to use &String
.
- Pros: Very cheap call.
- Cons: Need to store the id. Need to keep it up-to-date when the
title
orpage_num
fields change.
Use if accessed very frequently.
Return a Cow
This type is capable of representing either a borrowed or an owned thing, and via deref coercion acts like the borrowed thing in usage.
fn id(&self) -> Cow<str> {
match self.ty {
PageType::Type1 => Cow::Owned(format!("{}-{}", self.title, self.page_num)),
PageType::Type2 => Cow::Borrowed(&self.title),
}
}
- Pros: Efficient in the simple case. Doesn't increase struct size. Doesn't need complicated code to maintain the id.
- Cons: The usage is slightly more complicated, depending on what the user does with the result. Still allocates a new string in the complex case.
This makes a good default to use, unless you really want to keep the API as simple as possible.
There are three ways you can implement this, with different trade-offs.
Return an owned string
You return String
and use self.title.clone()
.
- Pros: Simple.
- Cons: Allocates a new string on every call, even in the simple case.
Use when you have no reason to think that this might become a performance issue, and you want the simplicity of simply returning String
.
Store the id in the struct
Build it in the constructor function. (Building it on-demand is also possible, but incurs complicated lifetime issues.) Return a &str
. There is hardly ever a good reason to use &String
.
- Pros: Very cheap call.
- Cons: Need to store the id. Need to keep it up-to-date when the
title
orpage_num
fields change.
Use if accessed very frequently.
Return a Cow
This type is capable of representing either a borrowed or an owned thing, and via deref coercion acts like the borrowed thing in usage.
fn id(&self) -> Cow<str> {
match self.ty {
PageType::Type1 => Cow::Owned(format!("{}-{}", self.title, self.page_num)),
PageType::Type2 => Cow::Borrowed(&self.title),
}
}
- Pros: Efficient in the simple case. Doesn't increase struct size. Doesn't need complicated code to maintain the id.
- Cons: The usage is slightly more complicated, depending on what the user does with the result. Still allocates a new string in the complex case.
This makes a good default to use, unless you really want to keep the API as simple as possible.
edited Jan 2 at 19:18
Shepmaster
159k15325468
159k15325468
answered Jan 2 at 7:33
Sebastian RedlSebastian Redl
50.6k476116
50.6k476116
2
"you could return a Cow, but that complicates usage of the method" : Isn't that the perfect use case for aCow
? Your comment makes it look like it's not the best solution here and I fear it might be badly interpreted.
– Denys Séguret
Jan 2 at 8:28
3
The perfect use case forCow
is when the efficiency gain is worth the usability loss. Since I don't know what the use case is, I can't say what the best way is. But I could formulate the post in a more neutral manner.
– Sebastian Redl
Jan 2 at 10:01
I don't understand what you mean by usability loss, Cow has been design to be a user friendly tool. Also in my opinion the most important is that cow feature have a overheat, people often forget that, small I agree, but always keep in mind that some feature doesn't come for free. (but that a free abstraction ofc)
– Stargateur
Jan 2 at 10:08
1
I've rewritten the post to be more balanced. The usability loss comes from having a wrapper. Yes, deref coercion means that many usages are the same, but under some circumstances, the user actually has to understand what having a cow means.
– Sebastian Redl
Jan 2 at 10:14
add a comment |
2
"you could return a Cow, but that complicates usage of the method" : Isn't that the perfect use case for aCow
? Your comment makes it look like it's not the best solution here and I fear it might be badly interpreted.
– Denys Séguret
Jan 2 at 8:28
3
The perfect use case forCow
is when the efficiency gain is worth the usability loss. Since I don't know what the use case is, I can't say what the best way is. But I could formulate the post in a more neutral manner.
– Sebastian Redl
Jan 2 at 10:01
I don't understand what you mean by usability loss, Cow has been design to be a user friendly tool. Also in my opinion the most important is that cow feature have a overheat, people often forget that, small I agree, but always keep in mind that some feature doesn't come for free. (but that a free abstraction ofc)
– Stargateur
Jan 2 at 10:08
1
I've rewritten the post to be more balanced. The usability loss comes from having a wrapper. Yes, deref coercion means that many usages are the same, but under some circumstances, the user actually has to understand what having a cow means.
– Sebastian Redl
Jan 2 at 10:14
2
2
"you could return a Cow, but that complicates usage of the method" : Isn't that the perfect use case for a
Cow
? Your comment makes it look like it's not the best solution here and I fear it might be badly interpreted.– Denys Séguret
Jan 2 at 8:28
"you could return a Cow, but that complicates usage of the method" : Isn't that the perfect use case for a
Cow
? Your comment makes it look like it's not the best solution here and I fear it might be badly interpreted.– Denys Séguret
Jan 2 at 8:28
3
3
The perfect use case for
Cow
is when the efficiency gain is worth the usability loss. Since I don't know what the use case is, I can't say what the best way is. But I could formulate the post in a more neutral manner.– Sebastian Redl
Jan 2 at 10:01
The perfect use case for
Cow
is when the efficiency gain is worth the usability loss. Since I don't know what the use case is, I can't say what the best way is. But I could formulate the post in a more neutral manner.– Sebastian Redl
Jan 2 at 10:01
I don't understand what you mean by usability loss, Cow has been design to be a user friendly tool. Also in my opinion the most important is that cow feature have a overheat, people often forget that, small I agree, but always keep in mind that some feature doesn't come for free. (but that a free abstraction ofc)
– Stargateur
Jan 2 at 10:08
I don't understand what you mean by usability loss, Cow has been design to be a user friendly tool. Also in my opinion the most important is that cow feature have a overheat, people often forget that, small I agree, but always keep in mind that some feature doesn't come for free. (but that a free abstraction ofc)
– Stargateur
Jan 2 at 10:08
1
1
I've rewritten the post to be more balanced. The usability loss comes from having a wrapper. Yes, deref coercion means that many usages are the same, but under some circumstances, the user actually has to understand what having a cow means.
– Sebastian Redl
Jan 2 at 10:14
I've rewritten the post to be more balanced. The usability loss comes from having a wrapper. Yes, deref coercion means that many usages are the same, but under some circumstances, the user actually has to understand what having a cow means.
– Sebastian Redl
Jan 2 at 10:14
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54002638%2fwhat-should-the-return-type-be-for-a-method-that-returns-str-or-new-string-with%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown