GoLand 2019.1 Help

Using extract and inline refactorings

With extract and inline refactorings, you can quickly clean up your code and make it more streamlined or explicit.

Extract a variable

  1. Select and right-click the following code fragment: &User{ ID: 1, Name: "Smith",}.

  2. Navigate to Refactor | Extract | Variable.

  3. Type u as a name for a new variable.

Extract a variable

Code snippet

package main import ( "errors" "fmt" "log" ) type User struct { ID int Name string } func findUser(user string) (*User, error) { if user != "smith" { return nil, errors.New("user not found") } return &User{ ID: 1, Name: "Smith", }, nil } func main() { user, err := findUser("smith") if err != nil { log.Fatalf("could not find user %s\n", "smith") } fmt.Printf("user found: %#v\n", user) }

Extract methods

  1. Select and right-click the following code fragment: &User{ ID: 1, Name: "Smith",}.

  2. Navigate to Refactor | Extract | Method.

Extract methods

Code snippet

package main import "fmt" type rect struct { width, height int } func main() { r := rect{width: 10, height: 5} perim := 2*r.width + 2*r.height area := r.width * r.height fmt.Println("area: ", area) fmt.Println("perim: ", perim) }

Extract a constant

  1. In the editor, select an expression or declaration of a variable you want to replace with a constant.

  2. Press Ctrl+Alt+C to introduce a constant or select Refactor | Extract | Constant.

    Select an expression you want to extract as constant and press Enter. Select the number of occurrences you want to replace and a name you want to use.

Example of the extract a constant refactoring

Code snippet

package main import "fmt" func plus(a int, b int) int { return a + b } func plusPlus(a, b, c int) int { return a + b + c } func main() { res := plus(1, 2) fmt.Println("1+2+3·=", res) res = plusPlus(1, 2, 3) fmt.Println("1+2+3·=", res) }

Extract a function or a method

  1. In the editor, select an expression or its part that you want to extract. You can also position the caret within the expression, in this case GoLand offers you a list of potential code selections.

  2. Press Ctrl+Alt+M or on the main menu, select Refactor | Extract | Extract Method.

  3. Type a method name and press Enter.

Example of the Extract a method refactoring

Code snippet

package main import "fmt" type rect struct { width, height int } func main() { r := rect{width: 10, height: 5} perim := 2*r.width + 2*r.height area := r.width * r.height fmt.Println("area: ", area) fmt.Println("perim:", perim) }
Last modified: 17 May 2019