Golang if/else not compiling - go

I cannot figure out why this will not compile.
It says functions ends without a return statement, but when I add a return after the else, it still won't compile.
func (d Foo) primaryOptions() []string{
if(d.Line == 1){
return []string{"me", "my"}
}
else{
return []string{"mee", "myy"}
}
}

Go forces else to be on the same line as the if brace.. because of its "auto-semicolon-insertion" rules.
So it must be this:
if(d.Line == 1) {
return []string{"me", "my"}
} else { // <---------------------- this must be up here
return []string{"mee", "myy"}
}
Otherwise, the compiler inserts a semicolon for you:
if(d.Line == 1) {
return []string{"me", "my"}
}; // <---------------------------the compiler does this automatically if you put it below
else {
return []string{"mee", "myy"}
}
..hence your error. I will link to the relevant documentation shortly.
EDIT: Effective Go has information regarding this.

Related

Argument passed to call that takes no arguments.. Firebase

Not sure why i'm getting this.. any suggestions would be grateful!
I ran into issues with my original coding where I had Firebase pod and Firebase Package.. so I started from scratch since that wasnt fixing itself.. now I get this.. and I am at a loss for how to resolve it.
static func fetchUsers() -> AnyPublisher<[UserProfile], Error> {
Future< [UserProfile], Error > { promise in
self.db.collection("Users")
.getDocuments { (snapshot, error) in
if let error = error {
promise(.failure(error))
return
}
guard let snapshot = snapshot else {
promise(.failure(FirebaseError.badSnapshot))
return
}
var users = [UserProfile]()
snapshot.documents.forEach { document in
print(users.count)
if let user = try? document.data(as: UserProfile.self){
if users.contains(where: { $0.id == user.id}) {return}
users.append(user)
} else {
print("Not working")
}
}
promise(.success(users))
}
}
.eraseToAnyPublisher()
}
I believe this is the syntax you're after:
var users = [UserProfile]()
users = snapshot.documents.compactMap { (document) -> UserProfile? in
if users.contains(where: { $0.id == user.id}) {
return nil
} else {
return try? document.data(as: UserProfile.self)
}
}
Also be aware that when you iterate something in Swift and encounter a false condition on an iteration, return will return out of the greater scope, not just that iteration. Therefore, use continue.
for x in y {
guard x > 0 else {
continue // continues loop
}
// ...
}

What is the meaning of `copyOnWriteContext` in module `github.com/google/btree`?

Recently, I read the source code of google/btree. But I'am conflused by the struct copyOnWriteContext. It is used in node function mutableFor, like following
func (n *node) mutableFor(cow *copyOnWriteContext) *node {
if n.cow == cow {
return n
}
fmt.Println("new node?")
out := cow.newNode()
if cap(out.items) >= len(n.items) {
out.items = out.items[:len(n.items)]
} else {
out.items = make(items, len(n.items), cap(n.items))
}
copy(out.items, n.items)
// Copy children
if cap(out.children) >= len(n.children) {
out.children = out.children[:len(n.children)]
} else {
out.children = make(children, len(n.children), cap(n.children))
}
copy(out.children, n.children)
return out
}
I review all the code in this module, and found that there is only one place create the copyOnWriteContext's instance. It is when the tree is created.
func New(degree int) *BTree {
return NewWithFreeList(degree, NewFreeList(DefaultFreeListSize))
}
So what is the meaning for mutableFor. Because there is only one copyOnWriteContext in the entire code. The n.cow always equals param cow.
n.cow can be nil.
// freeNode frees a node within a given COW context, if it's owned by that
// context. It returns what happened to the node (see freeType const
// documentation).
func (c *copyOnWriteContext) freeNode(n *node) freeType {
if n.cow == c {
// clear to allow GC
n.items.truncate(0)
n.children.truncate(0)
n.cow = nil
if c.freelist.freeNode(n) {
return ftStored
} else {
return ftFreelistFull
}
} else {
return ftNotOwned
}
}

How do you handle errors inside a Rust filter()?

I'd like to use a filter function that may return an Err result, and bubble it up to the containing function:
mycoll.into_iter()
.filter(|el| {
if el == "bad" {
Err(MyError)
} else {
Ok(el < "foo")
}
})
I found a good explanation on how to handle this type of case when it comes to map() (using .collect::<Result<...>>()): How do I stop iteration and return an error when Iterator::map returns a Result::Err? but I can't get a similar solution to work for filter().
What's the idiomatic solution here?
I'd probably suggest using filter_map. Your example would look like:
mycoll.into_iter()
.filter_map(|el| {
if el == "bad" {
Some(Err(MyError))
} else if el < "foo" {
Some(Ok(el))
} else {
None
}
})

How to populate Enum from the values retrieved from Database

Looking at the example here at Message Controller for Pizza Example, if I want to populate Size or Kind based on some user input and make a call to the database, how would I do that?
So far as I know, there is not an easy way to populate the Enum at runtime.
It looks like this hasn't been implemented yet. I took a look inside https://github.com/Microsoft/BotBuilder/blob/master/CSharp/Library/FormFlow/FormBuilder.cs and found this:
internal static void TypePaths(Type type, string path, List<string> paths)
{
if (type.IsClass)
{
if (type == typeof(string))
{
paths.Add(path);
}
else if (type.IsIEnumerable())
{
var elt = type.GetGenericElementType();
if (elt.IsEnum)
{
paths.Add(path);
}
else
{
// TODO: What to do about enumerations of things other than enums?
}
}
else
{
FieldPaths(type, path, paths);
}
}
else if (type.IsEnum)
{
paths.Add(path);
}
else if (type == typeof(bool))
{
paths.Add(path);
}
else if (type.IsIntegral())
{
paths.Add(path);
}
else if (type.IsDouble())
{
paths.Add(path);
}
else if (type.IsNullable() && type.IsValueType)
{
paths.Add(path);
}
else if (type == typeof(DateTime))
{
paths.Add(path);
}
}
Notice the TODO about enumerations other than enums.
Outside of the FormBuilder we can use PromptDialog.Choice which takes an IEnumerable<> of your options.
It is possible to chain dialogs together, so you may have to split your FormDialog into two with the PromptDialog in-between.
Alternatively take a fork of BotBuilder and implement the TODO!

A way to simplify these if statements

I've often run into this situation where I have a complicated if statement with a lot of inner if statements and a lot of repeated code. It essentially boils down to I have a bunch of cases and certain code blocks that execute based on those statements, but if a different condition is true then I want those code blocks to execute in different conditions. Here's a generic example:
if (condition) {
if (conditionA) {
codeBlockW;
}
else if (conditionB) {
codeBlockX;
}
else if (conditionC) {
codeBlockY;
}
else if (conditionD) {
codeBlockZ;
}
}
else {
if (conditionA) {
codeBlockZ;
}
else if (conditionB) {
codeBlockY;
}
else if (conditionC) {
codeBlockX;
}
else if (conditionD) {
codeBlockW;
}
}
if ((condition AND conditionA) OR (!condition AND conditionD)) { codeBlockW }
else if ((condition AND conditionB) OR (!condition AND conditionC)) { codeBlockX }
else if ((condition AND conditionC) OR (!condition AND conditionB)) { codeBlockY }
else if ((condition AND conditionD) OR (!condition AND conditionA)) { codeBlockZ }
You can shorten it a little bit like this maybe, I don't imagine any shorter way...

Resources