GoLand 2018.3 Help

Extract variable

Extract a variable

If you come across an expression that is hard to understand or it is duplicated in several places throughout you code, the Extract Variable refactoring can help you deal with those problems placing the result of such expression or its part into a separate variable that is less complex and easier to understand. Plus, it reduces the code duplication.

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

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

  3. Select a name suggested in the pop-up or type your own and press Enter. If GoLand finds more than one occurrence, it lets you specify whether or not you want to extract this variable for all of them.

Example of the Extract a variable refactoring

Code example: Extract a variable

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) }
Last modified: 6 February 2019