Syntax error unexpected else expecting

Parse error: syntax error, unexpected T_ELSE, expecting T_WHILE in Y:hometest1.ruwwwindex.php on line 660 Привожу код:...

За последние 24 часа нас посетили 11584 программиста и 1164 робота. Сейчас ищут 309 программистов …


  1. Tom_as

    Tom_as
    Активный пользователь

    С нами с:
    10 авг 2010
    Сообщения:
    3
    Симпатии:
    0

    Parse error: syntax error, unexpected T_ELSE, expecting T_WHILE in Y:hometest1.ruwwwindex.php on line 660

    Привожу код:

    1. $sel = isset( $_POST[‘sel’] ) ? $_POST[‘sel’] : isset( $_GET[‘sel’] ) ? $_GET[‘sel’] : «»;
    2.         if ( isset( $_COOKIE[‘dp_login’], $_COOKIE[‘dp_pass’] ) )
    3.             $strSQL = «SELECT id FROM «.USERS_TABLE.» WHERE login='».addslashes( $_COOKIE[‘dp_login’] ).«‘ AND password='».addslashes( $_COOKIE[‘dp_pass’] ).«‘ «;
    4.             $rs = $dbconn->execute( $strSQL );
    5.             if ( 0 < $rs->fields[0] )
    6.                 $user = auth_index_user( );
    7.             $user = auth_index_user( );
    8.                 if ( !isset( $_POST[‘remember_me’] ) )

    660 строка это последнее else между фигурными скобками. Не особо я понимаю чет в чем дело. если там должно быть while по тексту ошибки, то ошибка не исчезает.

    PHP, JavaScript, SQL и другой код пишите внутри тегов

    Код ( (Unknown Language)):
    1. [b]php][/b]Тут код[b][/[/b][b]code][/b][/color]


  2. WildZero

    WildZero
    Активный пользователь

    С нами с:
    24 фев 2010
    Сообщения:
    242
    Симпатии:
    0
    Адрес:
    Пермь

    Скобка перед последним else должна быть перед while.


  3. tommyangelo

    с вложенностью разберись, у тебя получилось do … else


  4. Tom_as

    Tom_as
    Активный пользователь

    С нами с:
    10 авг 2010
    Сообщения:
    3
    Симпатии:
    0

    я убрал сейчас из кода

    else
    {
    setcookie( «dp_login», «», time( ) — 7200 );
    setcookie( «dp_pass», «», time( ) — 7200 );
    }

    вот эту часть кода и все заработало….так я и не понял в смысле должна быть перед while

    ток потом правда еще одна ошибка появилась: Parse error: syntax error, unexpected ‘}’, expecting T_WHILE in Y:hometest1.ruwwwincludefunctions_index.php on line 85

    85я строчка это $id_lang_by_ip = $IpInfo->id_lang; после первого if

    1.     $file_name = isset( $_SERVER[‘PHP_SELF’] ) ? afterlastslash( $_SERVER[‘PHP_SELF’] ) : «index.php»;
    2.     $IpInfo = new ipinfo( $dbconn, $config );
    3.     if (!isset($_COOKIE[«language_cd»]) && GetSiteSettings(‘lang_ident_feature’)){
    4.         $id_lang_by_ip = $IpInfo->id_lang;
    5.         if ($id_lang_by_ip > 0 && $config[«default_lang»] != $id_lang_by_ip){
    6.             header(«location: index.php?language_code=».$id_lang_by_ip);
    7.     $elements = elementsforquicksearch( );
    8.     $smarty->assign( «elements», $elements );
    9.     banners( getrightmodulepath( __FILE__ ) );
    10.     $smarty->assign( «lang_link», getlangs( ) );

    PHP, JavaScript, SQL и другой код пишите внутри тегов

    Код ( (Unknown Language)):
    1. [b]php][/b]Тут код[b][/[/b][b]code][/b][/color]


  5. Roomlife

    Roomlife
    Активный пользователь

    С нами с:
    6 авг 2010
    Сообщения:
    34
    Симпатии:
    0

    там где у вас две скобки } (перед $elements = elementsforquicksearch( ); ) надо поставить третью, чтобы закрыть функцию


  6. Tom_as

    Tom_as
    Активный пользователь

    С нами с:
    10 авг 2010
    Сообщения:
    3
    Симпатии:
    0

    Блин точно, чет я даже и не заметил этого…спасибо огромное. эх…тяжело чужой код редактировать блин….


  7. WildZero

    WildZero
    Активный пользователь

    С нами с:
    24 фев 2010
    Сообщения:
    242
    Симпатии:
    0
    Адрес:
    Пермь

    Дак установи себе какой нибудь notepad++, и не мучайся ты со скобками.


  8. T0n

    С нами с:
    13 окт 2015
    Сообщения:
    1
    Симпатии:
    0

    Господа, та же проблема с «PHP Parse error: syntax error, unexpected T_ELSE» родилась при переезде на другой VPS. Код не менялся, а функционал закончился ((, причем хостер ссылается именно на эту ошибку при попытках разобраться. Итак, речь идет о подбросе фотки и последующем ее редактировании. Суть первого файла заключается в следующем:

    1. <p><strong>Выбирите файл для загрузки (до 5 MБ , с расширением jpg или gif):</strong></p>
    2.         <FORM ENCTYPE=»multipart/form-data» ACTION=»zagruzka_obrabotka.php» METHOD=POST>
    3. <p><INPUT NAME=»myfile» TYPE=»file»  size=»40″ size=»5Mb» class=»inputField»><br><br>
    4. <INPUT class=»dobav» TYPE=»submit» name=»button» VALUE=»Загрузить»></p>
    5. {echo «<strong>По такому запросу страница не сконфигурирована</strong>»;}
    6. Обработка во втором файле выглядит так:
    7. // права на папку посмотреть:
    8. //echo substr(sprintf(‘%o’, fileperms(‘/etc/passwd’)), -4);
    9.      //echo $_SERVER[‘DOCUMENT_ROOT’].$dir;
    10.  if (!is_dir($_SERVER[‘DOCUMENT_ROOT’].‘/’.$dir)){
    11. //chmod($_SERVER[‘DOCUMENT_ROOT’].$dir, 0777);
    12.         $src=$dir.$_FILES[«myfile»][«name»];    
    13.     $dest=«foto/$a/ava.jpg» ;
    14.       function img_resize_real($src, $dest, $width, $height, $rgb=0xFFFFFF, $quality=83)
    15.          if ($size === false) return false;
    16.          // Определяем исходный формат по MIME-информации, предоставленной
    17.          // функцией getimagesize, и выбираем соответствующую формату
    18.          // imagecreatefrom-функцию.
    19.          $icfunc = «imagecreatefrom» . $format;
    20.          if ($set_w == 0 && $set_h == 0) { $set_w = $src_w; $set_h = $src_h; }
    21.          if ($set_w > 0 && $set_h == 0)  { $set_h = ceil($src_h*$set_w/$src_w); }
    22.          if ($set_h > 0 && $set_w == 0)  { $set_w = ceil($src_w*$set_h/$src_h); }
    23.          $prc_w = ceil($src_w*$set_h/$src_h);
    24.          $prc_h = ceil($src_h*$set_w/$src_w);
    25.              $out_w = $set_w; $out_h = $prc_h;
    26.              $out_w = $prc_w; $out_h = $set_h;
    27.              $xw = ceil($set_w*$src_h/$set_h);
    28.              $src_x = ceil(($src_w$xw)/2);
    29.              $xh = ceil($set_h*$src_w/$set_w);
    30.              $src_y = ceil(($src_h$xh)/2);
    31.          if ($out_w > $set_w || $out_h > $set_h)
    32.                  $h = ceil($out_h*$set_w/$out_w); $w = $set_w;
    33.                  $w = ceil($out_w*$set_h/$out_h); $h = $set_h;
    34.              $w = $out_w; $h = $out_h;
    35.          // Создаем новое изображение
    36.          // Копируем существующее изображение в новое с изменением размера:
    37.          $idest,  // Идентификатор нового изображения
    38.          $isrc,  // Идентификатор исходного изображения
    39.          0,0,      // Координаты (x,y) верхнего левого угла
    40.          $src_x,$src_y, // Координаты (x,y) верхнего левого угла копируемого
    41.          // блока существующего изображения
    42.          $out_w,    // Новая ширина копируемого блока
    43.          $out_h,    // Новая высота копируемого блока
    44.          $size[0], // Ширина исходного копируемого блока
    45.          $size[1]  // Высота исходного копируемого блока
    46.          if ($aaa<>true) {echo «<strong>Произошла ошибка! Попробуйте еще раз</strong>»;} 
    47.          return array(‘width’ => $out_w, ‘height’=> $out_h);
    48.     if (img_resize_real(«$src«,«foto/$a/ava.jpg»,240, 320))
    49.     {echo ‘<strong>Фото успешно загружено</strong>’;
    50.     printf(‘<p>[url=»kabinet.php?a=%s»]Мой кабинет[/url]</p><br>’,$danie88[«id»]);
    51.         else                          ———————- МЕСТО УКАЗАНИЯ НА ОШИБКУ СИНТАКСИСА
    52.         {echo «<strong>По такому запросу страница не сконфигурирована</strong>»;}          ——— ПОСЛЕДНИЙ ВЫВОД
    53. else {echo «<strong>По такому запросу страница не сконфигурирована</strong>»;}

    Итак, два вопроса:
    1.Почему один и тот же код на разных серверах работает по-разному?
    2.Для обеспечения работоспособности продолжать пинать хостера или действительно, что-то подправить в скрипте?

    PHP, JavaScript, SQL и другой код пишите внутри тегов

    Код ( (Unknown Language)):
    1. [b]php][/b]Тут код[b][/[/b][b]code][/b][/color]

This is the  chapter 12 of the golang comprehensive tutorial series. Refer to this link for other chapters of the series – Golang Comprehensive Tutorial Series

Next Tutorial – Switch
Previous Tutorial – For Range loop

Now let’s check out the current tutorial. Below is the table of contents for current tutorial.

Overview

Go has if-else statement similar to any other programming language to perform the basic conditional logic. Below is the format for if-else statement in golang

if condition {
   //Do something
} else if condition {
   //Do something
} else {
   //Do something

Before we move further let’s talk about the condition first. Only a statement or a combination of statements that result in a boolean are allowed for a condition in if. false boolean is treated as false in a condition in go and true boolean is treated as true. As mentioned above, the condition can be composed of multiple statements combined by operators in Go such as &&, ||, >, <, >=, <=, ! etc.

Now let’s look into the if-else statement in detail to understand the small things. Go supports below formats for the if-else statement

  • Only if
  • If Else
  • If Else Ladder
  • Nested if-else
  • If with a short statement

if statement alone has below format

if condition {
   //Do something
}

If the condition is true then the statement inside the braces is executed.  Some points to note about if statement

  • Brackets can be omitted around the condition.
  • Opening and closing braces after condition are mandatory

Let’s see a working example. Below program checks if a number is greater than 5.

package main

import "fmt"

func main() {
    a := 6
    if a > 5 {
        fmt.Println("a is greater than 5")
    }
}

Output

a is greater than 5

Let’s see another example of multiple statement in a if condition. Below is a program to check if a number lies in a particular range. Notice that multiple statement in the condition are joined by the && operator.

package main

import "fmt"

func main() {
    a := 4
    if a > 3 && a < 6 {
        fmt.Println("a is within range")
    }
}

Output

a is within range

If Else Statement

If Else statement has below format

if condition {
   //Do something
} else {
   //Do something
}

If the condition is true then the statement inside the if block is executed otherwise the statement inside the else block is executed. Some points to note about if-else statement.

  • The else keyword should be on the same line as the closing brace for it. If not there will be below compiler error.
syntax error: unexpected else, expecting }

Let’s see a small example of if else statement. In below program we use if else statement to figure out the max number of 2 numbers

package main

import "fmt"

func main() {
    a := 1
    b := 2

    if a > b {
        fmt.Println("a is greater than b")
    } else {
        fmt.Println("b is greater than a")
    }
}

Output

b is greater than a

If Else Ladder

If Else ladder has the below format

if condition1 {
   //Do something
} else if condition2 {
   //Do something
} else {
  //Do something
}

Some points to note about this if else ladder

  • Any number of else if statement can be added in the middle
  • else if should lie on the same line as the previous closing brace

Below is a working code example. The code given an age is using a if else ladder to find out weather a person is «Kid», «Young» or «Old».

package main

import "fmt"

func main() {
    age := 29
    if age < 18 {
        fmt.Println("Kid")
    } else if age >= 18 && age < 40 {
        fmt.Println("Young")
    } else {
        fmt.Println("Old")
    }
}

Output:

Young

Nested If Else

Below are some one of the possible format for nested if else.

Only nested if

if condition {
  //Do something
  if condition2 { 
    //Do something
  }
  //Do something
}

Nested if else

if condition1 {
   //....
   if condition2 {
      //...
   } else {
      //...
   }
  //...
}

Below combination is also possible for nested if else

if condition1 {
   //...
} else {
   //...
   if condition2 {
      //...
   } else {
     //....
   }
   //....
}

Let’s see a working example of nested if else. In below program we print the max of three numbers using nested if else.

package main

import "fmt"

func main() {
    a := 1
    b := 2
    c := 3
    if a > b {
        if a > c {
            fmt.Println("Biggest is a")
        } else if b > c {
            fmt.Println("Biggest is b")
        }
    } else if b > c {
        fmt.Println("Biggest is b")
    } else {
        fmt.Println("Biggest is c")
    }
}

Output:

Biggest is c

If with short statement

If statement also supports a statement before the condition. This statement will be executed before the condition. There can also be new initialized variable in the statement. Below is the format for that.

if statement; condition {
   //Do something
}

The initialization if present in the statement will be a short declaration. Notice that var keyword is not supported in the statement. Let’s see a working example

package main

import "fmt"

func main() {
    if a := 6; a > 5 {
        fmt.Println("a is greater than 5")
    }
}

Output

a is greater than 5

The variable that is initialized in if statement is available inside all the branches. As in below example variable a is also available in the else block.

package main

import "fmt"

func main() {
    if a := 1; a > 5 {
        fmt.Println("a is greater than 5")
    } else {
        fmt.Println("a is less than 5")
    }
}

Output:

a is less than 5

If Conditions

We mentioned at the start that only boolean values or statement that result in boolean value are allowed in the if condition. Let’s see a working code of the error that comes in case of using any else than boolean

package main

import "fmt"

func main() {
    if 1 {
        fmt.Println("a is greater than 5")
    }
}

Output: Below compiler error is raised

non-bool 1 (type int) used as if condition

Ternary Operator

There is no ternary operator in Go, hence you need to use if else statements in place of that.

Conclusion

That is all about if else statement in go. Hope you have liked this article. Please share feedback/improvements/mistakes in comments

Next Tutorial – Switch
Previous Tutorial – For Range loop

  • complete
  • go
  • golang
  • guide
  • understand
  • using
    • Home
    • Forum
    • The Ubuntu Forum Community
    • Ubuntu Official Flavours Support
    • General Help
    • [SOLVED] SH SCRIPT Syntax error: «else» unexpected (expecting «then»)

    1. Angry SH SCRIPT Syntax error: «else» unexpected (expecting «then»)

      BTW, yes I did search for a solution but the only one I found said this error happened if I had an if statement on the same lines as «then».
      Can you guys help me out?
      Here is a part of my script,

      Code:

      if [ -f file1.jar ]; 
          then 
      echo "Found: file 1.jar" 
          else  
      echo "file1.jar: Missing " 
          Down  
      
        if [ -f file2.zip ]; 
         then 
      echo "Found: file2.zip" 
         else  
      echo "file2.zip: Missing " 
          Down  
      
        if [ -f file3.sh ]; 
         then 
      echo Found: file3.sh  
         else   
      echo file.sh: Missing  
          Down

      There alot more and «Down» was defined as a function

      Down() (
      echo «my script is a type of installing script if you needed to know,»
      echo «it Identifies files if there present, if not downloads them and moves them into a java game.»
      echo «I get a syntaz error on line 22 which is the else after found: file 1 echo»
      echo «I also have #!/bin/sh at the top, I didnt copy it in»
      )

      Can you help me out?

      Last edited by adrenalin6; March 9th, 2011 at 01:28 PM.

      Reason: Removed Spaces from previously tried fix


    2. Re: SH SCRIPT Syntax error: «else» unexpected (expecting «then»)

      use indentation because your script is unreadable and why all these empty lines?

      if syntax goes like this

      Code:

      if <condition>; then
        <stuff>
      else
        <stuff>
      fi

      or

      Code:

      if <condition>
      then
        <stuff>
      else
        <stuff>
      fi

      simply put newline and ; are synonymous in some cases.

      Last edited by Vaphell; March 9th, 2011 at 01:08 PM.


    3. Re: SH SCRIPT Syntax error: «else» unexpected (expecting «then»)

      you have to terminate a particular if with a corresponding fi..


    4. Re: SH SCRIPT Syntax error: «else» unexpected (expecting «then»)

      Quote Originally Posted by Vaphell
      View Post

      use indentation because your script is unreadable and why all these empty lines?

      if syntax goes like this

      Code:

      if <condition>; then
        <stuff>
      else
        <stuff>
      fi

      or

      Code:

      if <condition>
      then
        <stuff>
      else
        <stuff>
      fi

      simply put newline and ; are synonymous in some cases.

      I read somewhere to add lines because its what caused my error, sorry if it made it un readable.
      No reason for double posting, I tried it on the part of my script that was having problems, sorry but same error
      «./installer.sh: 22: Syntax error: «else» unexpected (expecting «then»)»

      Last edited by adrenalin6; March 9th, 2011 at 01:25 PM.


    5. Re: SH SCRIPT Syntax error: «else» unexpected (expecting «then»)

      Quote Originally Posted by neo_aryan
      View Post

      you have to terminate a particular if with a corresponding fi..

      Tell me if I understood

      Code:

      if < -f file1.sh >;
         then
      <echo "File1">
         else
      <echo "Failed">
          fi

      I read about fi but I concluded it acted like return 0; in C++ (for example)
      So it’s to finish an «if»?
      Also Same Problem

      Error Changed after doing some editing,
      its » ./installer.sh: 24: Syntax error: «else» unexpected (expecting «}») «

      the from the start to line 24 is

      Code:

      #!/bin/sh
      
      pause()
      {    read -n1 -t5 any_keyread -n1 -t5 any_key
          echo 
      }
      
      Start()
      {
       
      echo "Starting File Check"
      pause
       
      if [ -f crackedclient.jar ]; 
      
      then 
          {
      echo "Found: crackedclient.jar"
      } 
      else {
      echo "crackedclient.jar: Missing " 
          Down }
      fi

      I cleaned up the useless echo lines at the top but its all the way from start to line 23.
      (I will be AFK but I will be back in 7 hours)

      Last edited by adrenalin6; March 9th, 2011 at 01:53 PM.

      Reason: I may of got it wrong but I’m receiving the same syntax error on the same line.


    6. Re: SH SCRIPT Syntax error: «else» unexpected (expecting «then»)

      though i don know much but it is something like opening and closing braces in c++ so if you have if you should have a corresponding fi so that computer may understand which if ends here or something like that..go for a standard guide for better explanation but i think that fi is the problem for you


    7. Re: SH SCRIPT Syntax error: «else» unexpected (expecting «then»)

      don’t put < > there, i merely used them to indicate customizable parts of the expression , use real conditions in [] and normal commands. And with valid script you don’t need to put an empty line between every 2 lines of code. Below example works just fine

      Code:

      #!/bin/bash
      
      if [ -f file ]
      then
        echo line1
        echo line2
      else
        echo line3
      fi

      Last edited by Vaphell; March 9th, 2011 at 02:00 PM.


    8. Smile Re: SH SCRIPT Syntax error: «else» unexpected (expecting «then»)

      Thanks guys for help,
      but I epicly failed, I had a pause function that didnt work but didnt know.
      Now the script deleted the game files, folders and it self including all copys of itself.

      Moral is: DONT KEEP BACKUPS IN SAME FOLDER WITH A SCRIPT CONTAINING rm *.
      lol

      -Henry

      Last edited by adrenalin6; March 9th, 2011 at 10:08 PM.

      Reason: Added Humor (English not mother tongue)


    Bookmarks

    Bookmarks


    Posting Permissions

    Welcome to tutorial number 8 of our Golang tutorial series.

    if is a statement that has a boolean condition and it executes a block of code if that condition evaluates to true. It executes an alternate else block if the condition evaluates to false. In this tutorial, we will look at the various syntaxes and ways of using if statement.

    If statement syntax

    The syntax of the if statement is provided below

    if condition {  
    }
    

    If the condition is true, the lines of code between the braces { and } is executed.

    Unlike in other languages like C, the braces { } are mandatory even if there is only one line of code between the braces{ }.

    Example

    Let’s write a simple program to find out whether a number is even or odd.

    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        num := 10
        if num%2 == 0 { //checks if number is even
            fmt.Println("The number", num, "is even")
            return
        }
        fmt.Println("The number", num, "is odd")
    }
    

    Run in Playground

    In the above program, the condition num%2 in line no. 9 finds whether the remainder of dividing num by 2 is zero or not. Since it is 0 in this case, the text The number 10 is even is printed and the program returns.

    If else statement

    The if statement has an optional else construct which will be executed if the condition in the if statement evaluates to false.

    if condition {  
    } else {
    }
    

    In the above snippet, if condition evaluates to false, then the lines of code between else { and } will be executed.

    Let’s rewrite the program to find whether the number is odd or even using if else statement.

    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        num := 11
        if num%2 == 0 { //checks if number is even
            fmt.Println("the number", num, "is even")
        } else {
            fmt.Println("the number", num, "is odd")
        }
    }
    

    Run in playground

    In the above code, instead of returning if the condition is true as we did in the previous section, we create an else statement that will be executed if the condition is false. In this case, since 11 is odd, the if condition is false and the lines of code within the else statement is executed. The above program will print.

    the number 11 is odd  
    

    If … else if … else statement

    The if statement also has optional else if and else components. The syntax for the same is provided below

    if condition1 {  
    ...
    } else if condition2 {
    ...
    } else {
    ...
    }
    

    The condition is evaluated for the truth from the top to bottom.

    In the above statement if condition1 is true, then the lines of code within if condition1 { and the closing brace } are executed.

    If condition1 is false and condition2 is true, then the lines of code within else if condition2 { and the next closing brace } is executed.

    If both condition1 and condition2 are false, then the lines of code in the else statement between else { and } are executed.

    There can be any number of else if statements.

    In general, whichever if or else if‘s condition evaluates to true, it’s corresponding code block is executed.
    If none of the conditions are true then else block is executed.

    Let’s write a program that uses else if.

    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        num := 99
        if num <= 50 {
            fmt.Println(num, "is less than or equal to 50")
        } else if num >= 51 && num <= 100 {
            fmt.Println(num, "is between 51 and 100")
        } else {
            fmt.Println(num, "is greater than 100")
        }
    }
    

    Run in playground

    In the above program, the condition else if num >= 51 && num <= 100 in line no. 11 is true and hence the program will print

    99 is between 51 and 100  
    

    If with assignment

    There is one more variant of if which includes an optional shorthand assignment statement that is executed before the condition is evaluated. Its syntax is

    if assignment-statement; condition {  
    }
    

    In the above snippet, assignment-statement is first executed before the condition is evaluated.

    Let’s rewrite the program which finds whether the number is even or odd using the above syntax.

    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        if num := 10; num % 2 == 0 { //checks if number is even
            fmt.Println(num,"is even") 
        }  else {
            fmt.Println(num,"is odd")
        }
    }
    

    Run in playground

    In the above program num is initialized in the if statement in line no. 8. One thing to be noted is that num is available only for access from inside the if and else. i.e. the scope of num is limited to the if else blocks. If we try to access num from outside the if or else, the compiler will complain. This syntax often comes in handy when we declare a variable just for the purpose of if else construct. Using this syntax in such cases ensures that the scope of the variable is only within the if else statement.

    Gotcha

    The else statement should start in the same line after the closing curly brace } of the if statement. If not the compiler will complain.

    Let’s understand this by means of a program.

    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        num := 10
        if num % 2 == 0 { //checks if number is even
            fmt.Println("the number is even") 
        }  
        else {
            fmt.Println("the number is odd")
        }
    }
    

    Run in playground

    In the program above, the else statement does not start in the same line after the closing } of the if statement in line no. 11. Instead, it starts in the next line. This is not allowed in Go. If you run this program, the compiler will output the error,

    ./prog.go:12:5: syntax error: unexpected else, expecting }
    

    The reason is because of the way Go inserts semicolons automatically. You can read about the semicolon insertion rule here https://golang.org/ref/spec#Semicolons.

    In the rules, it’s specified that a semicolon will be inserted after closing brace }, if that is the final token of the line. So a semicolon is automatically inserted after the if statement’s closing braces } in line no. 11 by the Go compiler.

    So our program actually becomes

    ...
    if num%2 == 0 {  
          fmt.Println("the number is even") 
    };  //semicolon inserted by Go Compiler
    else {  
          fmt.Println("the number is odd")
    }
    

    after semicolon insertion. The compiler would have inserted a semicolon in line no. 4 of the above snippet.

    Since if{...} else {...} is one single statement, a semicolon should not be present in the middle of it. Hence this program fails to compile. Therefore it is a syntactical requirement to place the else in the same line after the if statement’s closing brace }.

    I have rewritten the program by moving the else after the closing } of the if statement to prevent the automatic semicolon insertion.

    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        num := 10
        if num%2 == 0 { //checks if number is even
            fmt.Println("the number is even") 
        } else {
            fmt.Println("the number is odd")
        }
    }
    

    Run in playground

    Now the compiler will be happy and so are we 😃.

    Idiomatic Go

    We have seen various if-else constructs and we have in fact seen multiple ways to write the same program. For example, we have seen multiple ways to write a program that checks whether the number is even or odd using different if else constructs. Which one is the idiomatic way of coding in Go? In Go’s philosophy, it is better to avoid unnecessary branches and indentation of code. It is also considered better to return as early as possible. I have provided the program from the previous section below,

    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        if num := 10; num % 2 == 0 { //checks if number is even
            fmt.Println(num,"is even") 
        }  else {
            fmt.Println(num,"is odd")
        }
    }
    

    Run in playground

    The idiomatic way of writing the above program in Go’s philosophy is to avoid the else and return from the if if the condition is true.

    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        num := 10;
        if num%2 == 0 { //checks if number is even
            fmt.Println(num, "is even")
            return
        }
        fmt.Println(num, "is odd")
    
    }
    

    Run in playground

    In the above program, as soon as we find out the number is even, we return immediately. This avoids the unnecessary else code branch. This is the way things are done in Go 😃. Please keep this in mind whenever writing Go programs.

    This brings us to the end of this tutorial. I hope you enjoyed reading. Please leave your valuable comments and feedback.

    If you would like to advertise on this website, hire me, or if you have any other development requirements please email to naveen[at]golangbot[dot]com.

    Next tutorial — Loops

    Понравилась статья? Поделить с друзьями:
  • Syntax error unexpected character after line continuation character
  • Syntax error unexpected bash array
  • Syntax error the requested module dell does not provide an export named default
  • Syntax error python что это
  • Syntax error python примеры