Expecting an 'else'

from collections import Optional

@value
struct NetworkInfo:
    var target: String
    var prot: String
    var opt: String
    var source: String
    var dest: String
    var service: Optional[String]

    
    fn get_service(self) -> Optional[String]
        if self.service: # expecting an 'else' followed by an expression
            _full_service_entry = self.service.value()
            try:
                service_list = _full_service_entry.split(' ')
                for item in service_list:
                    if item[].find('dpt:') != -1:
                        _dpt = item[].split(':')
                        if len(_dpt) >= 2:
                            return _dpt[1]
            except:
                return None
        else: # unknown tokens at the end of a declaration
            return None

def main():
    var x = NetworkInfo('my_target', 'my_prot', 'my_opt', 'my_source', 'my_dest', String('tcp dpt:http flags:FIN,SYN,RST,ACK/SYN'))
    var the_service = x.get_service()
    print(x.target)
    print(the_service.value())

Curious why my first “if” and then the “else” are getting errors (added the errors as comments). Seems the “if” is expecting an “else” but then doesn’t see the “else” ? In VS Code, I don’t see any improper indentation.

Also, is there a way to preview a new post before posting? No idea how ugly this is gonna be :sweat_smile:

Hi @AffableHoneyBadger! You should be able to see a side-by-side preview of your post before creating it (see screenshot below)

If the outer if evaluates to true, and the inner if statements all evalue to false, the we would have executed all the code in the function without returning anything.

Thanks @Caroline ! I didn’t see it, but now I realize why. I was seeing the “Welcome to Modular” message instead which was sitting on top of the preview! ha! Oops!

1 Like

Missing a colon after the return type, and also the else should just be a plain return

fn get_service(self) -> Optional[String]:
        if self.service:
            _full_service_entry = self.service.value()
            try:
                service_list = _full_service_entry.split(' ')
                for item in service_list:
                    if item[].find('dpt:') != -1:
                        _dpt = item[].split(':')
                        if len(_dpt) >= 2:
                            return _dpt[1]
            except:
                return None
        return None

@akneni @bgreni Solved! Thank you both! I think it was a combination of what each you said. Working now! Time for more playing!

Edit. Shoot, can only mark one “solution” - I think it was both answers.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.