Go 不算新語言,但這兩年它長出了不少有意思的特性,採用它的知名專案也在快速增加。既然寫過一篇關於 SitePoint 所用語言的整理,行動端的支持自然就成了必須研究的題目。
Android 支持 Go 這件事毫不意外:兩者都出自 Google;而另一個推動力,大概是不少開發者心裡那個「用 Go 取代 Java」的念頭。
你需要 Go 1.5 以上的版本,接著安裝 GoMobile 工具鏈,它負責編譯與執行 Android、iOS 產物:
go get golang.org/x/mobile/cmd/gomobile gomobile init
官方範例放在 GoLangInstalldir/src/golang.org/x/mobile/example/ 底下,若尚未下載:
go get -d golang.org/x/mobile/example/basic
對很多應用來說,編譯純 Go 版本時忽略平台相關的庫是可以接受的。此時可用的功能子集包括:App 控制與配置、OpenGL ES 2、資源管理、事件管理,以及一批實驗性套件(OpenAL、audio、font、sprite、運動感測器等)。
gomobile build -target=android golang.org/x/mobile/example/basic gomobile install golang.org/x/mobile/example/basic
gomobile build -target=ios golang.org/x/mobile/example/basic
iOS 沒有統一的部署指令,你得用自己熟悉的方式把產物送到裝置或模擬器,例如 ios-deploy。上面的流程也可以套在 audio 範例上試試。
不必精通 Go 也能讀懂它。開頭是幾個 import:
import (
"golang.org/x/mobile/app"
"golang.org/x/mobile/asset"
...
)
如果你去 GoLangInstalldir/src/golang.org/x/mobile/* 翻一翻,會發現那些被編進來源的 Java 與 Objective-C 檔案;再往下看,就能找到程式碼對 app、glctx 等套件的引用。
我們可以用 Go 寫出緊湊且最佳化過的原生應用,但它還不是「原生風格」——所有相依庫仍是 Java 或 Objective-C / Swift。Go Mobile 團隊提供了另一條路:把 Go 套件(也就是你的程式)綁定進原生應用。共享公共 Go 邏輯時這招很好用,上手快,長期維護則需多花心思。
用 Android Studio 匯入 GoLangInstalldir/src/golang.org/x/mobile/example/bind/android,打開 build.gradle(hello 模組),更新 GOPATH 與 Go 的路徑,同步 Gradle 後即可部署到模擬器或真機。
注意:此方式目前只支援 ARM 架構的裝置與模擬器。
// MainActivity.java
package org.golang.example.bind;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import go.hello.Hello;
public class MainActivity extends Activity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.mytextview);
// 直接呼叫 Go 函式
String greetings = Hello.Greetings("Android and Gopher");
mTextView.setText(greetings);
}
}
// hello.go
package hello
import "fmt"
func Greetings(name string) string {
return fmt.Sprintf("Hello, %s!", name)
}
透過 import go.hello.Hello 引入對應 Go 檔,Java 端就能以 Hello.Greetings 呼叫,步驟並不繁瑣。
cd GoLang_Install_dir/src/golang.org/x/mobile/example/bind gomobile bind -target=ios golang.org/x/mobile/example/bind/hello
這會在目前目錄產生 Hello.framework。在 Xcode 打開 bind.xcodeproj,把 Hello.framework 拖進專案(需要時勾選 Copy items),就能在 Objective-C 中直接呼叫:
#import "ViewController.h"
#import "hello/Hello.h" // gomobile bind 產生的標頭檔
@implementation ViewController
@synthesize textLabel;
- (void)loadView {
[super loadView];
textLabel.text = GoHelloGreetings(@"iOS and Gopher");
}
@end
Swift 專案同樣可用:
let msg = Hello.GoHelloGreetings("gopher")
坦白說,多數情況並不值得。如果你已經在用 Go 寫應用、也不在意是否原生風格,那就繼續放手做,因為建置與部署 Go 原生應用確實很簡單。若願意投入精力嘗試綁定,能走得更遠,但仍需有所節制。
如果你目前沒在用 Go,那暫時不必為了開發原生行動應用而考慮它。不過我有很強的預感:在不久之後,Go 會成為這塊極具潛力的選項。